实现思路
- 在 React 组件的
state
中定义一个标志位,用于判断事件是否已经绑定。
- 创建需要绑定和解绑的事件处理函数。
- 在
render
方法中,根据 state
中的标志位来决定按钮点击时执行绑定事件还是解绑事件的逻辑。
关键代码
import React, { Component } from 'react';
class ButtonComponent extends Component {
constructor(props) {
super(props);
this.state = {
isBound: false
};
this.handleClick = this.handleClick.bind(this);
this.eventHandler = this.eventHandler.bind(this);
}
eventHandler() {
console.log('事件被触发');
}
handleClick() {
if (this.state.isBound) {
window.removeEventListener('click', this.eventHandler);
} else {
window.addEventListener('click', this.eventHandler);
}
this.setState({
isBound: !this.state.isBound
});
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isBound? '解绑事件' : '绑定事件'}
</button>
);
}
}
export default ButtonComponent;