gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 16:06:46 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com