簡體   English   中英

堆疊的父子組件未觸發子組件的onClick事件

[英]onClick event of child component is not getting triggered for stacked parent and child component

我有以下兩個組件,分別具有onClick()處理函數。 問題是doSomethingElse永遠都不會獲取,而是直接調用doSomething

<ParentComponent onClick={this.doSomething}>
   <ChildComponent onClick={this.doSomethingElse} />
</Parent>

Child被示出為在像proover parent使用z-index

class Parent extends React.Component {
  constructor(props) {
    super(props);

  }

  handleP = (e) => {
    alert("parent")
  };

  render() {
    return (

      <div onClick={this.handleP} style={{
        left: 100,
        top: 100,
        zIndex: 100,
        position: 'absolute',
      }}>
      Parent Text
        <Child  />
      </div>          

    )
  }
}

class Child extends React.Component {
  constructor(props) {
    super(props);

  }

  handleC = (e) => {
    alert("child")
  };

  render() {
    return (

      <div onClick={this.handleC} style={{
        left: 1,
        top: 1,
        zIndex: 1000,
        position: 'absolute',
      }}>
      Child Text  
      </div>          

    )
  }
}



React.render(
  <Parent />,
  document.getElementById('react_example')
); 

Jsbin

@SandipPingle的問題是因為默認情況下,單擊事件會一直冒到窗口。 因此,在調用子處理程序之后,事件會冒泡到父組件。 為此,您需要停止事件傳播。 請參閱此問題和此沙箱 ,以基於此答案的示例固定版本:)

暫無
暫無

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

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