javascript - 单击子项时触发子项和父项的 onClick

标签 javascript reactjs

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

    this.handleChild = this.handleChild.bind(this);
    this.handleParent = this.handleParent.bind(this);
  }

  render() {
    return (
      <div
        style={{width: '100%', height: '500px', background: 'white'}}
        onClick={this.handleParent}>

        <div
          style={{ width: '40px', height: '40px', margin: '0 auto', background: 'black'}}
          onClick={this.handleChild}>
          hello
        </div>

      </div>
    );
  }

  handleParent(e) {
    console.log('parent');
  }

  handleChild(e) {
    console.log('child');
  }
}

点击子项时的输出

child
parent

期望输出是

child

我的意思是我只想在点击 child 时触发 child 的 onClick。

parent 工作正常。单击父级时,它仅触发父级的 onClick。 我遇到的问题是 child 。

最佳答案

您需要在子处理程序中停止传播

handleChild(e) {
  e.stopPropagation();
  console.log('child');
}

stopPropagation - Prevents further propagation of the current event in the capturing and bubbling phases.

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

    this.handleChild = this.handleChild.bind(this);
    this.handleParent = this.handleParent.bind(this);
  }

  render() {
    return (
      <div
        style={{width: '100%', height: '500px', background: 'white'}}
        onClick={this.handleParent}>

        <div
          style={{ width: '40px', height: '40px', margin: '0 auto', background: 'black'}}
          onClick={this.handleChild}>
          hello
        </div>

      </div>
    );
  }

  handleParent(e) {
    console.log('parent');
  }

  handleChild(e) {
    e.stopPropagation();
    console.log('child');
  }
}

ReactDOM.render(<Sample />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

关于javascript - 单击子项时触发子项和父项的 onClick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39470071/

相关文章:

javascript - 放大简单的 pdf.js 查看器

javascript - 为什么这个 javascript 正则表达式 split 函数不起作用?

javascript - react 引导表未对齐

reactjs - React 上下文 API 的选择器?

javascript - KonvaJS 中的文本水平和垂直居中

javascript - 在 react js中获取文件类型

javascript - 提交时将 div 图像上传到数据库

javascript - 将文本转换为其他格式

javascript - firebase.auth.currentUser 返回 null 直到在表单中输入内容

javascript - 实现搜索栏按钮和文件树组件