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
}