reat 阻止事件冒泡
时间: 2023-09-07 08:16:51 浏览: 80
在React中,要阻止事件冒泡,可以使用e.stopPropagation()方法。这个方法会停止事件在组件内部的冒泡传播。在React中,通过给元素添加事件处理函数来注册事件。当事件触发时,事件对象e会作为参数传递给事件处理函数。通过调用e.stopPropagation()方法,可以阻止事件继续向父组件传播。
例如,在React组件中,如果想要阻止事件冒泡,可以在事件处理函数中使用e.stopPropagation()方法。示例代码如下:
```
import React, { Component } from 'react';
class App extends Component {
handleClickTestBox = (e) => {
console.warn('handleClickTestBox: ', e);
}
handleClickTestBox2 = (e) => {
console.warn('handleClickTestBox2: ', e);
}
handleClickTestBox3 = (e) => {
e.stopPropagation();
console.warn('handleClickTestBox3: ', e);
}
render() {
return (
<div className="test-box" onClick={this.handleClickTestBox}>
<div onClick={this.handleClickTestBox2}>
<div onClick={this.handleClickTestBox3}></div>
</div>
</div>
);
}
}
export default App;
```
在上面的代码中,通过在点击事件处理函数handleClickTestBox3中调用e.stopPropagation()方法,可以阻止事件冒泡。这样,当点击最内层的div时,只会触发handleClickTestBox3函数,而不会触发handleClickTestBox2和handleClickTestBox函数。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [react中阻止事件冒泡](https://blog.csdn.net/w799766/article/details/82591372)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* [React 阻止事件冒泡](https://blog.csdn.net/weixin_44461275/article/details/124639651)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文