[英]Reactjs keeps throwing error “TypeError: this.goActive is not a function”
我有一個函數,用於檢測用戶是否處於活動狀態。 但是,一旦我移動鼠標,它就會引發錯誤TypeError: this.goActive is not a function
來自resetTimer(e)
TypeError: this.goActive is not a function
,但是如果我自己運行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文檔中閱讀更多內容https://reactjs.org/docs/handling-events.html
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.