由React.createRef()创建的ref在子componentDidMount上为null

时间:2018-10-27 15:29:54

标签: reactjs react-dom

我正在尝试将引用从父级传递到子级组件,但是当我访问子级componentDidMount内的引用时,它不像我通过的其他道具(如函数)那样立即可用。

class Parent extends Component{
  constructor(){
   super();
   this.parentElem = React.createRef();
  }

render(){
 return(
  <div>
    <div ref={this.parentElem}>
        I can be seen by child
    </div>
    <Child parentElem={this.parentElem}/>
  </div>
 )

}

}

孩子

  class Child extends Component{

    componentDidMount(){
       console.log(this.props.parentElem.current) // null but looking at react dev tools its there
    }
    render(){
     return(
      <div>
     ....
      </div>
     )

    }

    }

版本

"react": "^16.3.1",
"react-dom": "^16.3.1",

0 个答案:

没有答案