React Refs discussions

1. The role of Refs

Through Refs, you can access

1. DOM node.

2. The React element created in the render method. (Example of class component)

2. What is the use of accessing nodes or instances? Why use Refs to access it?

Demand scenarios for accessing nodes or instances:

  • Manage focus, text selection or media playback.
  • Trigger mandatory animation.
  • Integrate third-party DOM libraries

Because in some scenarios, in React, you can't solve it without using Refs.

3. Piecemeal knowledge

1. Refs can be used on DOM elements or class components. However, it cannot be used on function components. This is because there are no instances of function components.

2. If you want to pass ref to the DOM element or class component in the function component, you can achieve it by using forwardRef.

3. Through useImperativeHandle, the parent component of the function component can obtain the operation method of the DOM element or class component in the child component of the component.

 

Reference materials:

[1] React.Refs and the DOM.https://reactjs.bootcss.com/docs/refs-and-the-dom.html

[2] React.Refs forwarding. Https://reactjs.bootcss.com/docs/forwarding-refs.html

[3] React.useImperativeHandle.https://reactjs.bootcss.com/docs/hooks-reference.html#useimperativehandle

 

Guess you like

Origin www.cnblogs.com/toLivetoLearn/p/12722641.html