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
我的意思是当点击子元素时,只触发子元素的onClick事件。
父元素已经正常工作。当点击父元素时,只会触发父元素的onClick事件。 问题出在子元素上。
e.stopPropagation();
可以阻止父元素的事件继续传播。 - Sasikumar