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。 我遇到的问题是带着孩子。
答案 0 :(得分:5)
您需要在子处理程序中停止传播,
handleChild(e) {
e.stopPropagation();
console.log('child');
}
stopPropagation
- 防止进一步传播当前事件 捕捉和冒泡阶段。
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>