Javascript 访问window.onkeydown事件内部的本地函数
试图在此窗口内调用我的函数之一。onkeydown函数,但我超出范围。你知道我能做什么吗Javascript 访问window.onkeydown事件内部的本地函数,javascript,reactjs,function,ecmascript-6,scope,Javascript,Reactjs,Function,Ecmascript 6,Scope,试图在此窗口内调用我的函数之一。onkeydown函数,但我超出范围。你知道我能做什么吗 componentDidMount() { setTimeout(() => { window.onkeydown = function(e) { if (e.keyCode === 13) { console.log("Enter detected"); // this.handleNextCard(); // this function wi
componentDidMount() {
setTimeout(() => {
window.onkeydown = function(e) {
if (e.keyCode === 13) {
console.log("Enter detected");
// this.handleNextCard(); // this function will throw an error: undefined
}
};
}, 250);
}
componentWillUnmount() {
window.onkeydown = null;
}
handleFlipCard() {
this.props.toggleViewAnswer();
}
handleNextCard() {
this.props.selectNextCard();
}
render(){}
尝试对
键下处理程序使用另一个箭头函数-它将继承其this
:
window.onkeydown = e => {
if (e.keyCode === 13) {
console.log("Enter detected");
this.handleNextCard();
}
}
在使用箭头功能之前,可以通过以下方式完成:
componentDidMount() {
setTimeout(() => {
var that = this;
window.onkeydown = function(e) {
if (e.keyCode === 13) {
console.log("Enter detected");
that.handleNextCard();
}
};
}, 250);
}
@杰克巴什福德:没错,关键是要以另一种方式进入scope@Noob很酷,这有助于我更好地理解这个问题。此对象有两个,我们希望确保选择了正确的一个。