有我无权访问的 XYZ 组件。现在我想检测 如果单击该组件。
render () {
return(
<XYZ className="abc" ref={node => {this.pop = node}} /> // Note, I don't have access to XYZ component
)}
阅读各种文章我发现了这一点:
handleClickOutside(e){
if (this.pop.contains(e.target)){
// not clicked outside
}
}
我收到Contains is undefined
,因为this.pop
是一个React组件
。怎么解决这个问题?
最佳答案
您可以使用 ReactDOM.findDOMNode 来获取 DOM 节点的引用 -
handleClickOutside(e) {
if(this.pop) {
const domNode = ReactDOM.findDOMNode(this.pop)
if(this.pop.contains(e.target)) {
//
}
}
}
由于 findDOMNode 在 React 16 中已弃用,并将在未来版本中删除 - 您可以尝试的另一件事是将 XYZ 组件包装在 div 内,并检查该 div 上的点击情况。
render () {
return(
<div onClick={this.handleContainerClick}>
<XYZ className="abc" ref={node => {this.pop = node}} /> // Note, I don't have access to XYZ component
</div>
)}
}
关于reactjs - 如果 this.node 是 react 组件的引用,则 this.node.contains 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50133673/