react如何阻止冒泡失败
生活随笔
收集整理的這篇文章主要介紹了
react如何阻止冒泡失败
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
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、當(dāng)用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;
相關(guān)免費學(xué)習(xí)推薦:JavaScript(視頻)
總結(jié)
以上是生活随笔為你收集整理的react如何阻止冒泡失败的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SEO的工作职责就是让网站拥有更多的关键
- 下一篇: jquery如何检查字符串中是否包含指定