簡體   English   中英

如果this.node是ref響應組件,this.node.contains不起作用

[英]this.node.contains does not work if this.node is a ref to react component

有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 component 怎么解決這個?

您可以使用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>
  )}
}

目前的答案是使用current屬性。

myRef = React.createRef();

const checkIfContains = e => {
    if (myRef.current.contains(e.target)) {
        doSomething();
    }
}

<div ref={myRef} onClick={checkIfContains} />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM