<! DOCTYPEhtml>
<html>
<head>
<meta charset="UTF-8" />
<title>React binds events to the body and prevents events from bubbling</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/[email protected]/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 id="root"></div>
<script type="text/babel">
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make 'this' work in the callback
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} id="m-btn">
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />.document.getElementById('root'));</script>
</body>
</html>
Copy the code