ReactJS移除ES6中的绑定事件处理程序

ReactJS remove bound event handlers in ES6

本文关键字:绑定 事件处理 程序 移除 ES6 ReactJS      更新时间:2023-09-26

我试图取消绑定ES6 react组件中的事件侦听器。我不确定这是不是最好的方法。

export default class ProductDetail extends React.Component {
    ...
    componentDidMount() {
        this.boundKeyListener = this.keyListener.bind(this);
        document.addEventListener('keydown', this.boundKeyListener);
    }
    componentWillUnmount(){
        document.removeEventListener('keydown', this.boundKeyListener);
    }
    ...
}

this.keylistener的内部,我需要做一个this.setState({foo:'bar'}),我发现在类的范围内运行侦听器的唯一方法是使用fn.bind()

我的问题是,我真的需要保存boundListener属性吗?或者

document.removeEventListener('keydown', this.keyListener.bind(this));

是足够的吗?

document.removeEventListener('keydown', this.keyListener.bind(this));

是足够的吗?

不会的。.bind返回新的函数,因此您将尝试删除与添加的处理程序不同的处理程序。

function foo() {}
console.log(foo.bind(null) === foo.bind(null));