问题描述
我有一个父项和一个子项。我需要在子组件中访问父级的 HTMLelement
。
I have a parent and a child component. I need to access the parent's HTMLelement
in the child component.
我有一个可行的但不干净的解决方案,涉及
this.setState({domNode:ReactDOM.findDOMNode(this)});
在父级的 componentDidMount
中在许多级别上都是错误的。
I have a working but unclean solution involvingthis.setState({ domNode: ReactDOM.findDOMNode(this) });
in the parent's componentDidMount
which is just wrong on many levels.
我该如何在父级中使用 createRef()
来传递其引用作为对孩子的支持,然后如何从引用中获取类型为 HTMLElement
的DOM节点?
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?
推荐答案
不涉及任何黑客的最佳解决方案是将函数从父级传递到子级,该函数返回要访问的元素的引用
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
父项:
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>
)
}
孩子:
getParentRef = () => {
const elem = this.props.getParentElem();
}
这篇关于从父级到子级传递React Ref以获得DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!