簡體   English   中英

單擊包含span的div,不會觸發onclick事件 - React

[英]Clicking on a div that contains span, doesn't trigger onclick event - React

我有一個div,在里面我根據某些條件渲染范圍。 如果該組件有一些孩子,我希望這個div擴展。 如果我在內跨區域外的區域上單擊此div,它可以正常工作。

一個例子,是下面的圖像 單擊該行時,它會展開區域以顯示此類項目。 但是,當我單擊標題文本時,它不起作用,on click事件不會觸發。

這是我的代碼:

 <div className={headerStyles.header} onClick={(e) => this.selectHeader(e, this.props.items.length)}>
    {this.props.items.length > 0 && 
          <span className={headerStyles.expand} style={{ color: this.props.headerNameColor }}></span>
                    }
          <span style={{ color: this.props.headerNameColor }}  >{this.props.headerName}</span>
                    {this.props.headerUrl &&
                        <a
                            style={{ color: this.props.headerNameColor }}
                            href={this.props.headerUrl}
                            data-interception="off"
                            target="_blank"
                            title="Open link in a new tab">
                            <i className={['ms-Icon', 'ms-Icon--OpenInNewWindow', headerStyles.openNewTab].join(' ')}></i>
                        </a>
                    }
                </div>

這是單擊標題時調用的函數:

 selectHeader(e, numOfItems) {
        if (e.target.children.length > 0 && numOfItems > 0) {
            e.target.children[0].classList.toggle(headerStyles.expand)
            e.target.children[0].classList.toggle(headerStyles.collapse)
            e.target.parentElement.querySelector(`.${headerStyles.items}`).classList.toggle(headerStyles.hidden)
        }
        else if(this.props.headerUrl){

        }
    }

任何指導表示贊賞。

謝謝

我懷疑你正在嘗試使用selectHeaderevent.target值。 這將無法正常工作,因為event.target將根據您在div中單擊的元素而改變。 它並不總是外部的“父”元素。

您還試圖從DOM中強制讀取數據,這不是一種非常“反應”的做事方式。 實際上,在你的函數中你正在做一個classList.toggle(headerStyles.hidden) ,這與React管理應用程序的狀態和呈現有直接沖突。 您需要的所有數據都應該在React應用程序的狀態內 - 您根本不需要查詢DOM。

Ditch event.targetclassList.toggle並找到一種使用React狀態的方法。 例如,當您單擊div時,您只需切換組件的“展開”狀態,並使用該狀態來確定要呈現的CSS類:

<div onClick={() => {this.setState({isExpanded: !this.state.isExpanded})}} >
  <span className={this.state.isExpanded ? headerStyles.expand : headerStyles.collapse} ></span>
</div>

避免在JSX中使用箭頭函數。 e對象總是被傳遞,因為這是一個事件處理程序,你的props可以從你的處理程序訪問:

selectHeader = (e) => {
     const numOfItems = this.props.items.length;
     // rest of the code...

 }

內部渲染方法:

<div onClick={this.selectHeader}>

嘗試將pointerEvents: 'none'樣式添加到span標記中,這樣就不會獲得任何鼠標事件。 這將使event.target始終為div

暫無
暫無

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

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