Home >Web Front-end >Front-end Q&A >How to cancel bubbling in react
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.
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('root')) // 给dom 元素绑定一个单击事件 重新渲染组件 就会把之前的 App组件 卸载了 document.onclick=function(){ ReactDOM.render(<div>Hello React.js</div>,document.getElementById('root')) } // 这样虽然实现了 但是出现了新的问题 因为给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!