我實現了一個香草JS倒計時進入反應成分如下:陣營倒計時錯誤
import React, { Component } from 'react';
class CustomCountDown extends Component {
constructor(props) {
super(props);
this.endTime;
this.msLeft;
this.time;
this.hours;
this.mins;
this.element;
}
twoDigits(n){
return (n <= 9 ? "0" + n : n);
}
updateTimer() {
this.msLeft = this.endTime - (+new Date);
if (this.msLeft < 1000) {
element.innerHTML = "countdown's over!";
} else {
this.time = new Date(this.msLeft);
this.hours = this.time.getUTCHours();
this.mins = this.time.getUTCMinutes();
this.element.innerHTML = (this.hours ? this.hours + ':' + this.twoDigits(this.mins) : this.mins) + ':' + this.twoDigits(this.time.getUTCSeconds());
setTimeout(this.updateTimer, this.time.getUTCMilliseconds() + 500);
}
}
countdown(elementName, minutes, seconds) {
this.element = document.getElementById(elementName);
this.endTime = (+new Date) + 1000 * (60*minutes + seconds) + 500;
this.updateTimer();
}
componentDidMount() {
this.countdown("count", 1, 30);
}
render() {
return(
<div id="count">
</div>
);
}
}
export default CustomCountDown;
我想不通爲什麼我收到以下錯誤:
需要綁定'this'(反應組件的上下文)與'updateTimer'功能,把這個線在構造函數中:'this.updateTimer =這.updateTimer.bind(this)' –
謝謝你解決了! – Alex
您的任何函數都沒有適當的綁定。你需要綁定你引用屬於React類上下文的'this'變量的每個函數 –