Home >Web Front-end >Front-end Q&A >How to cancel bubbling in react

How to cancel bubbling in react

藏色散人
藏色散人Original
2022-12-27 13:54:322538browse

React method to cancel bubbling: 1. Bind a click event to the dom element and re-render the component; 2. Use the "function change(e){e.nativeEvent.stopImmediatePropagation();}" method Just cancel the bubbling.

How to cancel bubbling in react

The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.

How to cancel bubbling in react?

Cancel bubbling in react

Recently I was doing a small demo to uninstall react components and encountered a small problem, which is the processing of bubbling events

We are in react Uninstalling components can be uninstalled by re-rendering

ReactDOM.render(<App />,document.getElementById(&#39;root&#39;))
//  给dom 元素绑定一个单击事件  重新渲染组件 就会把之前的 App组件 卸载了
document.onclick=function(){
    ReactDOM.render(<div>Hello React.js</div>,document.getElementById(&#39;root&#39;))
}
// 这样虽然实现了 但是出现了新的问题 因为给document 绑定的单击事件 导致 冒泡事件发生了
// 然后就开始尝试各中 取消冒泡的方式 在组件中
e.stopPropagation()
e.cancelBuble=true;
// 上面我知道的俩种方式都不可以 后来去网上搜索了一下 终于找到 藏得很深的取消冒泡的方法
 function  change(e){
     //  注意 在 react的事件对象中 是由react组件 给封装了一下
    e.nativeEvent.stopImmediatePropagation();  // 这个方法就可以做到了 nativeEvent 原生方法
}

Recommended learning: "react video tutorial"

The above is the detailed content of How to cancel bubbling in react. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn