在window.onkeydown事件中访问本地函数

时间:2019-06-28 23:11:46

标签: javascript reactjs function ecmascript-6 scope

尝试在此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(){}

2 个答案:

答案 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);
}