Câu hỏi phỏng vấn React.js
Câu hỏi

Làm thế nào để có thể tạo ref trong React?

Câu trả lời

Trong ReactJS, ref là một cách để truy cập trực tiếp một nút DOM hoặc một instance của một component trong React. Để tạo ref, bạn có thể sử dụng React.createRef() trong class components hoặc useRef() hook trong function components.

Class Components

Trong class components, bạn thường tạo ref bằng cách sử dụng React.createRef() trong constructor và sau đó gắn ref này vào một phần tử JSX bằng cách sử dụng thuộc tính ref.

import React, { Component } from 'react';

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }

  componentDidMount() {
    console.log(this.myRef.current); // Truy cập đến nút DOM hoặc component instance
  }

  render() {
    return <div ref={this.myRef}>Hello, World!</div>;
  }
}

Function Components

Trong function components, bạn có thể sử dụng useRef() hook để tạo ref. useRef trả về một đối tượng ref mà bạn có thể gắn vào ph...

middle

middle

Gợi ý câu hỏi phỏng vấn

middle

Bạn sẽ sử dụng flushSync trong ReactJS khi nào?

middle

mapStateToPropsmapDispatchToProps trong redux là gì?

middle

Portal trong React là gì?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào