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.

javascript Copy
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

Life Cycle trong React hoạt động như thế nào?

senior

Làm sao để ngăn các React component re-render?

senior

Trong React, tại sao cần liên kết các event handler với this?

Bình luận

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

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