React组件中window.onkeydown事件调用组件函数作用域问题求助
解决React类组件中window.onkeydown回调的作用域问题
这个场景我太熟悉了!问题出在普通函数作为window.onkeydown回调时,this的指向会变成window,而不是你的组件实例,所以调用this.handleNextCard()才会报undefined错误。下面给你3种简单有效的解决办法:
方法1:使用箭头函数(最推荐)
箭头函数不会绑定自己的this,它会继承定义时所在上下文的this(也就是componentDidMount里的组件实例)。直接把回调改成箭头函数就行:
componentDidMount() { setTimeout(() => { window.onkeydown = (e) => { if (e.keyCode === 13) { console.log("Enter detected"); this.handleNextCard(); // 现在this正确指向组件实例啦 } }; }, 250); }
方法2:提前缓存组件实例的this
在回调外面把组件的this存到一个变量(比如that)里,然后在普通函数里用这个变量调用方法:
componentDidMount() { const that = this; // 缓存组件实例的this setTimeout(() => { window.onkeydown = function(e) { if (e.keyCode === 13) { console.log("Enter detected"); that.handleNextCard(); // 用that代替this,指向组件实例 } }; }, 250); }
方法3:用bind绑定this
通过bind方法给回调函数绑定组件的this,这样回调里的this就会强制指向组件实例:
componentDidMount() { setTimeout(() => { window.onkeydown = function(e) { if (e.keyCode === 13) { console.log("Enter detected"); this.handleNextCard(); } }.bind(this); // 绑定组件的this到当前函数 }, 250); }
额外提示
你已经在componentWillUnmount里清理了window.onkeydown = null,这一点做得非常好!能避免组件卸载后还残留事件监听导致的内存泄漏问题。
内容的提问来源于stack exchange,提问作者jeninja
相关产品推荐
相关产品推荐

