这篇文章主要介绍react怎样阻止冒泡失败,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
react阻止冒泡失败的方法:1、在没有涉及到原生事件注册只有react事件时,用【e.stopPropagation()】阻止冒泡;2、需要用到【e.nativeEvent.stopImmediatePropagation()】方法。
react阻止冒泡失败的方法:
1、在没有涉及到原生事件注册只有react事件时,用e.stopPropagation()
阻止冒泡,代码如下:
import React, { Component } from 'react'; import './App.css'; 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;
2、当用document.addEventListener
注册了原生的事件后,用e.stopPropagation()是不能阻止与document之间的冒泡,这时候需要用到e.nativeEvent.stopImmediatePropagation()
方法,代码如下:
import React, { Component } from 'react'; import './App.css'; class App extends Component { componentDidMount() { document.addEventListener('click', this.handleDocumentClick, false); } handleDocumentClick = (e) => { console.log('handleDocumentClick: ', e); } handleClickTestBox = (e) => { console.warn('handleClickTestBox: ', e); } handleClickTestBox2 = (e) => { console.warn('handleClickTestBox2: ', e); } handleClickTestBox3 = (e) => { // 阻止合成事件的冒泡 e.stopPropagation(); // 阻止与原生事件的冒泡 e.nativeEvent.stopImmediatePropagation(); 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;
3、阻止合成事件与非合成事件(除了document)之间的冒泡,以上两种方式都不适用,需要用到e.target
判断, 代码如下:
import React, { Component } from 'react'; import './App.css'; class App extends Component { componentDidMount() { document.addEventListener('click', this.handleDocumentClick, false); document.body.addEventListener('click', this.handleBodyClick, false); } handleDocumentClick = (e) => { console.log('handleDocumentClick: ', e); } handleBodyClick = (e) => { if (e.target && e.target === document.querySelector('#inner')) { return; } console.log('handleBodyClick: ', e); } handleClickTestBox = (e) => { console.warn('handleClickTestBox: ', e); } handleClickTestBox2 = (e) => { console.warn('handleClickTestBox2: ', e); } handleClickTestBox3 = (e) => { // 阻止合成事件的冒泡 e.stopPropagation(); // 阻止与原生事件的冒泡 e.nativeEvent.stopImmediatePropagation(); console.warn('handleClickTestBox3: ', e); } render() { return ( <div className="test-box" onClick={this.handleClickTestBox} > <div onClick={this.handleClickTestBox2} > <div id="inner" onClick={this.handleClickTestBox3} > </div> </div> </div> ); } } export default App;
以上是react怎样阻止冒泡失败的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。