How do I access refs of a child component in the parent component

后端 未结 6 853
梦如初夏
梦如初夏 2020-11-29 23:41

If I have something like


  
  
  

And I want to access from

6条回答
  •  悲&欢浪女
    2020-11-30 00:12

    Using Ref forwarding you can pass the ref from parent to further down to a child.

    const FancyButton = React.forwardRef((props, ref) => (
      
    ));
    
    // You can now get a ref directly to the DOM button:
    const ref = React.createRef();
    Click me!;
    
    1. Create a React ref by calling React.createRef and assign it to a ref variable.
    2. Pass your ref down to by specifying it as a JSX attribute.
    3. React passes the ref to the (props, ref) => ... function inside forwardRef as a second argument.
    4. Forward this ref argument down to by specifying it as a JSX attribute.
    5. When the ref is attached, ref.current will point to the DOM node.

    Note The second ref argument only exists when you define a component with React.forwardRef call. Regular functional or class components don’t receive the ref argument, and ref is not available in props either.

    Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too.

    Reference: React Documentation.

提交回复
热议问题