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

Forwarding Refs trong React đển làm gì?

Câu trả lời

Forwarding Refs trong React là một kỹ thuật cho phép bạn chuyển một ref tự động qua một component để nó có thể truy cập đến một phần tử DOM con hoặc một instance của class component con. Điều này thường cần thiết khi bạn muốn một component cha có thể tương tác trực tiếp với một phần tử DOM hoặc component con mà không cần phải thêm các props trung gian hoặc logic bổ sung.

Cách Sử Dụng Forwarding Refs

Để sử dụng forwarding refs, bạn sẽ sử dụng hàm React.forwardRef để tạo một component. Hàm này nhận vào một hàm render và trả về một component React. Hàm render này nhận vào propsref như là tham số và trả về một React element.

Ví dụ:

const MyInput = React.forwardRef((props, ref) => (
  <input ref={ref} {...props} />
));

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

  focusInput = () => {
    this.inputRef.current.focus();
  };

  render() {
    return (
      <>
        <MyInput ref={this.inputRef} />
        <button onClick={this.focusInput}>Foc...
middle

middle

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

middle

Làm thế nào để truyền dữ liệu từ component con sang component cha trong React?

expert

So sánh redux thunkredux saga?

senior

React khác với AngularJS (1.x) như thế nào?

Bình luận

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

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