首页 > 解决方案 > 单击子元素时如何停止父元素上的单击事件

问题描述

我在 div 中有一个按钮。在他们的点击事件中,我正在执行两种不同的功能。要求是当子元素被点击时,父元素的onClick事件不应该触发。

redirectCTD() 
{
   console.log("inside Parent Element");
   //other stuffs to do
}  

openTileModal(toolName) 
{
  console.log("inside Child Element");
  this.setState({
   isOpenTile: true,
   toolSelected: toolName
  });
}



<div className="col-md-12 tool ctd_tool" onClick={this.redirectCTD}>
                          <button onClick={this.openTileModal.bind(this,"ctd")}><img src={require("../../../images/icon-expand-blue.png")} /></button>
</div>

我曾尝试使用event.stopPropogationand event.preventDefaultinsideopenTileModal()方法。

openTileModal(toolName,event) 
{
  event.stopPropogation();
  console.log("inside Child Element");
  this.setState({
   isOpenTile: true,
   toolSelected: toolName
  });
}

但这不起作用,我在控制台中遇到错误,“ e.stopPropogation is not a function”。有人可以帮助我实现目标。提前致谢

标签: reactjs

解决方案


你拼写Propagation错误。尝试这个:

openTileModal(toolName,event) 
{
  event.stopPropagation();
  console.log("inside Child Element");
  this.setState({
   isOpenTile: true,
   toolSelected: toolName
  });
}

推荐阅读