Pass React Ref from parent to child in order to get DOM element

有些话、适合烂在心里 提交于 2020-01-23 07:20:51

问题


I have a parent and a child component. I need to access the parent's HTMLelement in the child component.

I have a working but unclean solution involving this.setState({ domNode: ReactDOM.findDOMNode(this) }); in the parent's componentDidMount which is just wrong on many levels.

How can i do this using createRef() in the parent to pass its ref as a prop to the child and then how do i get the DOM node with type HTMLElement from the ref?


回答1:


The best solution that doesn't involve any hack would be to pass a function from parent to child that return the ref of the element to be access

Parent:

constructor(props) {
    super(props);
    this.domElem = React.createRef();
}

getElem = () => {
    return this.domElem;
}

render() {
    return (
       <div>
           <div id="elem" ref={this.domElem}>Test Elem</div>
           <Child getParentElem={this.getElem}/>
       </div>
    )
}

Child:

getParentRef = () => {
   const elem = this.props.getParentElem();
}


来源:https://stackoverflow.com/questions/54940884/pass-react-ref-from-parent-to-child-in-order-to-get-dom-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!