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

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

If I have something like


  
  
  

And I want to access from

6条回答
  •  北海茫月
    2020-11-30 00:17

    Recommended for React versions prior to 16.3

    If it cannot be avoided the suggested pattern extracted from the React docs would be:

    import React, { Component } from 'react';
    
    const Child = ({ setRef }) => ;
    
    class Parent extends Component {
        constructor(props) {
            super(props);
            this.setRef = this.setRef.bind(this);
        }
    
        componentDidMount() {
            // Calling a function on the Child DOM element
            this.childRef.focus();
        }
    
        setRef(input) {
            this.childRef = input;
        }
    
        render() {
            return 
        }
    }
    

    The Parent forwards a function as prop bound to Parent's this. When React calls the Child's ref prop setRef it will assign the Child's ref to the Parent's childRef property.

    Recommended for React >= 16.3

    Ref forwarding is an opt-in feature that lets some components take a ref they receive, and pass it further down (in other words, “forward” it) to a child.

    We create Components that forward their ref with React.forwardRef. The returned Component ref prop must be of the same type as the return type of React.createRef. Whenever React mounts the DOM node then property current of the ref created with React.createRef will point to the underlying DOM node.

    import React from "react";
    
    const LibraryButton = React.forwardRef((props, ref) => (
      
    ));
    
    class AutoFocus extends React.Component {
      constructor(props) {
        super(props);
        this.childRef = React.createRef();
        this.onClick = this.onClick.bind(this);
      }
    
      componentDidMount() {
        this.childRef.current.focus();
      }
    
      onClick() {
        console.log("fancy!");
      }
    
      render() {
        return ;
      }
    }
    

    Forwarding refs HOC example

    Created Components are forwarding their ref to a child node.

    function logProps(Component) {
      class LogProps extends React.Component {
        componentDidUpdate(prevProps) {
          console.log('old props:', prevProps);
          console.log('new props:', this.props);
        }
    
        render() {
          const {forwardedRef, ...rest} = this.props;
    
          // Assign the custom prop "forwardedRef" as a ref
          return ;
        }
      }
    
      // Note the second param "ref" provided by React.forwardRef.
      // We can pass it along to LogProps as a regular prop, e.g. "forwardedRef"
      // And it can then be attached to the Component.
      return React.forwardRef((props, ref) => {
        return ;
      });
    }
    

    See Forwarding Refs in React docs.

提交回复
热议问题