尝试在此window.onkeydown函数中调用我的一个函数,但超出范围。有什么想法我可以做什么?
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(){}
答案 0 :(得分:2)
尝试为keydown
处理程序使用另一个箭头函数-它会继承其this
:
window.onkeydown = e => {
if (e.keyCode === 13) {
console.log("Enter detected");
this.handleNextCard();
}
}
答案 1 :(得分:1)
在执行箭头功能之前,可以这样操作:
componentDidMount() {
setTimeout(() => {
var that = this;
window.onkeydown = function(e) {
if (e.keyCode === 13) {
console.log("Enter detected");
that.handleNextCard();
}
};
}, 250);
}