react阻止冒泡失敗的方法:1、在沒(méi)有涉及到原生事件注冊(cè)只有react事件時(shí),用【e.stoppropagation()】阻止冒泡;2、需要用到【e.nativeevent.stopimmediatepropagation()】方法。
react阻止冒泡失敗的方法:
1、在沒(méi)有涉及到原生事件注冊(cè)只有react事件時(shí),用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、當(dāng)用document.addeventlistener注冊(cè)了原生的事件后,用e.stoppropagation()是不能阻止與document之間的冒泡,這時(shí)候需要用到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;相關(guān)免費(fèi)學(xué)習(xí)推薦:javascript(視頻)