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

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

If I have something like


  
  
  

And I want to access from

6条回答
  •  误落风尘
    2020-11-30 00:01

    Here is an example that will focus on an input using refs (tested in React 16.8.6):

    The Child component:

    class Child extends React.Component {
      constructor(props) {
        super(props);
        this.myRef = React.createRef();
      }
      render() {
        return ();
      }
    }
    

    The Parent component with the Child component inside:

    class Parent extends React.Component {
      constructor(props) {
        super(props);
        this.childRef = React.createRef();
      }
      componentDidMount() {
        this.childRef.current.myRef.current.focus();
      }
      render() {
        return ;
      }
    }
    
    ReactDOM.render(
        ,
        document.getElementById('container')
    );
    

    The Parent component with this.props.children:

    class Parent extends React.Component {
        constructor(props) {
            super(props);
            this.childRef = React.createRef();
        }
        componentDidMount() {
            this.childRef.current.myRef.current.focus();
        }
        render() {
            const ChildComponentWithRef = React.forwardRef((props, ref) =>
                React.cloneElement(this.props.children, {
                    ...props,
                    ref
                })
            );
            return 
        }
    }
    
    ReactDOM.render(
        
            
        ,
        document.getElementById('container')
    );
    

提交回复
热议问题