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(影片)
以上是react如何阻止冒泡失敗的詳細內容。更多資訊請關注PHP中文網其他相關文章!