Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Reactjs不断抛出错误“;TypeError:this.goActive不是函数;_Javascript_Reactjs - Fatal编程技术网

Javascript Reactjs不断抛出错误“;TypeError:this.goActive不是函数;

Javascript Reactjs不断抛出错误“;TypeError:this.goActive不是函数;,javascript,reactjs,Javascript,Reactjs,我有一个功能,用于检测用户是否处于活动状态。但只要我移动鼠标,它就会抛出一个错误TypeError:this.goActive不是resetTimer(e)的函数,但是如果我自己运行resetTimer(e),我就会在控制台中得到我的“oy”。 这是我的密码: var timeoutID; class App extends Component { setup() { window.addEventListener("mousemove", this.resetTimer, fal

我有一个功能,用于检测用户是否处于活动状态。但只要我移动鼠标,它就会抛出一个错误
TypeError:this.goActive不是
resetTimer(e)
的函数,但是如果我自己运行
resetTimer(e)
,我就会在控制台中得到我的“oy”。 这是我的密码:

var timeoutID;
class App extends Component {


 setup() {
    window.addEventListener("mousemove", this.resetTimer, false);
    window.addEventListener("mousedown", this.resetTimer, false);
    window.addEventListener("keypress", this.resetTimer, false);
    window.addEventListener("DOMMouseScroll", this.resetTimer, false);
    window.addEventListener("touchmove", this.resetTimer, false);
    window.addEventListener("MSPointerMove", this.resetTimer, false);

    this.startTimer();
}


 startTimer() {
    // wait 2 seconds before calling goInactive
    timeoutID = window.setTimeout(this.goInactive, 2000);
}

 resetTimer(e) {
    window.clearTimeout(timeoutID);
    this.goActive();
}

 goInactive() {
     console.log("gah");
}

 goActive() {
    console.log("oy");
    this.startTimer();
}

render() {
    this.setup()
...

您需要将
resetTimer
中的
this
的上下文绑定到您的组件。
阅读React官方文档中的更多内容

您需要将
中的
的上下文绑定到您的组件。
阅读官方React文档中的更多内容

重置计时器的作用域是在回调中调用它的控件,在您的案例中是窗口

您需要将函数绑定到正确的作用域:

this.resetTimer = this.resetTimer.bind(this);
类内构造函数:

class App extends Component {
  constructor(...args) {
    super(...args);
    this.resetTimer = this.resetTimer.bind(this);
    // and all the other class methods
  }

  // here go method declarations
}
或者,您可以使用箭头语法(在ES6中),因此您可以将计时器重置为:

class App extends Component {
  resetTimer = (e) => {
    // code 
  }

  // and other method declarations
}

resetTimer
的作用域是在回调中调用它的控件,在您的案例中是窗口

您需要将函数绑定到正确的作用域:

this.resetTimer = this.resetTimer.bind(this);
类内构造函数:

class App extends Component {
  constructor(...args) {
    super(...args);
    this.resetTimer = this.resetTimer.bind(this);
    // and all the other class methods
  }

  // here go method declarations
}
或者,您可以使用箭头语法(在ES6中),因此您可以将计时器重置为:

class App extends Component {
  resetTimer = (e) => {
    // code 
  }

  // and other method declarations
}