React 在body上绑定事件以及阻止事件冒泡

react

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8" />

<title>React 在body上绑定事件以及阻止事件冒泡</title>

<script src="https://unpkg.com/react@16/umd/react.development.js"></script>

<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

<style>

html{height: 100%;}

body{height: 100%;background-color: rgba(0,0,0,0.2);}

.m-outer{background-color: red;}

</style>

</head>

<body>

<div ></div>

<script type="text/babel">

class Toggle extends React.Component {

constructor(props) {

super(props);

this.state = {isToggleOn: true};

// 这个绑定是必要的,使`this`在回调中起作用

this.handleClick = this.handleClick.bind(this);

}

componentDidMount() {

document.body.addEventListener('click', e => {

if (e.target && e.target.matches('#m-btn')) {

return;

}

console.log('body');

});

}

componentWillUnmount() {

document.body.removeEventListener('click');

}

handleClick() {

this.setState(prevState => ({

isToggleOn: !prevState.isToggleOn

}));

}

render() {

return (

<button onClick={this.handleClick} >

{this.state.isToggleOn ? 'ON' : 'OFF'}

</button>

);

}

}

ReactDOM.render(

<Toggle />,

document.getElementById('root')

);

</script>

</body>

</html>

以上是 React 在body上绑定事件以及阻止事件冒泡 的全部内容, 来源链接: utcz.com/z/381350.html

回到顶部