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

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

If I have something like


  
  
  

And I want to access from

6条回答
  •  萌比男神i
    2020-11-30 00:18

    1. Inside the child component add a ref to the node you need
    2. Inside the parent component add a ref to the child component.
    /*
    * Child component
    */
    class Child extends React.Component {
      render() {
        return (
          

    { this.heading = node; }}> Child

    ); } } /* * Parent component */ class Parent extends React.Component { componentDidMount() { // Access child component refs via parent component instance like this console.log(this.child.heading.getDOMNode()); } render() { return (
    { this.child = node; }} />
    ); } }

    Demo: https://codepen.io/itsfadnis/pen/aLWVVx?editors=0011

提交回复
热议问题