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;相关免费学习推荐:javascript(视频)
什么是域名的所有权 怎么证明购买的域名是我的域名实名制成功了域名验证未通过去年天猫双11类目榜单出炉酷狗音乐怎么下载到u盘 酷狗音乐歌曲下载到u盘的方法域名解析不到服务器解析到服务器打开后提示解析错误如何实现php字符转ascii?个人购买云服务器优惠12.10 Nginx访问日志 12.11 Nginx日志切割12.12 静态文件不记录日志和过期时间