Win*_*ten 3 javascript reactjs
我在父组件中有一个子组件。我想在我点击父级内部的任何地方时发出警报消息,除非点击子级。
class TodoApp extends React.Component {
constructor(props) {
super(props)
this.state = {
}
}
render() {
return (
<div className="parent" onClick={() => alert('x')}>
<p>Alert clicks anywhere on this div</p>
<div className="children">
<button>Do not alert On this element click</button>
</div>
<p>Alert clicks anywhere on this div</p>
</div>
)
}
}
Run Code Online (Sandbox Code Playgroud)
代码示例在这里:
小智 8
将 e.stopPropagation() 添加到子 onClick 属性
class TodoApp extends React.Component {
constructor(props) {
super(props)
this.state = {
}
}
render() {
return (
<div className="parent" onClick={() => alert('x')}>
<p>Alert clicks anywhere on this div</p>
<div onClick={(e) => e.stopPropagation()} className="children">
<button>Do not alert On this element click</button>
</div>
<p>Alert clicks anywhere on this div</p>
</div>
)
}
}
Run Code Online (Sandbox Code Playgroud)
您可以防止子元素中的事件传播,即
<button onClick={((e) => e.stopPropagation())}>Do not alert On this element click</button>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
970 次 |
| 最近记录: |