Câu hỏi phỏng vấn Reactjs
Câu hỏi

How to create refs in React?

Câu trả lời

To create refs in React, you can use either the React.createRef() method for class components or the useRef hook for functional components. Here's how you can use each method:

Using React.createRef() in Class Components

Introduced in React 16.3, React.createRef() creates a ref object that you can attach to React elements via the ref attribute. This method is typically used in class components. Here's an example:

import React, { Component } from 'react';

class MyComponent extends Component {
  constructor(props) {
    super(props);
    // Create a ref object using React.createRef()
    this.myRef = React.createRef();
  }

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

export default MyComponent;

In this example, this.myRef is attached to a <div> element. Once the component mounts, this.myRef.current will point to the corresponding DOM node[3][7][10].

Using useRef Hook in Functional Components

The useRef hook is part of React's Hooks API introduced in React 16.8. It works similarly to createRef but is used in functional components. Here's how you can use it:

import React, { useRef } from 'react';

function MyComponent() {
  // Create a ref object using useRef()
  const myRef = useRef(null);

  return <div ref={myRef}>Hello, World!</div>;
}

export default MyComponent;

In this example, myRef is initialized ...

junior

junior

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

entry

How would you write an inline style in React?

middle

What would be the common mistake of function being called every time the component renders?

junior

What is the purpose of using super constructor with props argument in React?

Bình luận

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

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