What are refs in React?

前端 未结 4 685
终归单人心
终归单人心 2021-02-09 05:38

I\'m having trouble understanding what refs are in React. I understand that it\'s a callback function and you put it in the render function, but beyond that I can\'t understand

4条回答
  •  孤街浪徒
    2021-02-09 06:03

    React has typical way of handling children. It does it with use of props in a top-down way. And to modify the child you have to re-render with new props. But there are cases where you want to modify/handle child outside of this typical flow. In these cases you use refs.

    Ref is an attribute that takes a callback and this callback is called whenever the component is mounted or unmounted. Refs can be added to both dom elements or components. Example:

    return (
      
    { this.textInput = input; }} />
    ); return ( { this.childComponent = component; }} {...props} /> );

    Whenever the component is mounted the ref callback is called with dom element or the child component instance. And whenever the component is unmounted its called with null.

    Now you can use this.textInput or this.childComponent and call its different available methods on it.


    Refs can be given to only either DOM elements or class component. They don't work on functional components. Example:

    function MyFunctionalComponent(props) {
      return ;
    }
    
    return (
       { this.childComponent = component; }}
        {...props}
      />
    );
    

    Refs should be used only when its absolutely necessary as they give you direct access to the element/component in DOM.

提交回复
热议问题