Gij*_*rts 3 javascript reactjs
我是 React 新手,我尝试构建一个计时器组件。现在我已经开始工作了,但我还想通过 onclick 处理程序停止计时器。问题是启动函数使用了一个间隔,但我不知道如何从另一个函数停止该间隔。
我的JS代码
constructor() {
super();
this.state = {
times: [],
timer: false,
currentTimer: 0
}
this.startTimer = this.startTimer.bind(this);
this.stopTimer = this.stopTimer.bind(this);
}
startTimer() {
const start = Date.now();
this.setState({ timer: true });
var timer = setInterval(() => {
let time = new Date() - start;
this.setState({ currentTimer: Math.round(time / 1000)});
}, 1000);
}
stopTimer() {
this.setState({ timer: false });
console.log('stopped');
//Clear interval here
}
Run Code Online (Sandbox Code Playgroud)
我知道该timer变量是该间隔的标识符,但我如何访问它然后停止它?我几乎尝试了所有方法,但似乎都不起作用,我只是不知道如何解决这个问题。
要停止计时器,您需要计时器 id,因此第一项工作是以可在所有类方法中访问的方式存储 id。第二项工作将用于clearInterval清除计时器(此处需要计时器 ID)。
一种选择是,将计时器 ID 存储在类实例中。
像这样:
startTimer() {
const start = Date.now();
this.setState({ timer: true });
// storing the id
this.timerID = setInterval(() => {
let time = new Date() - start;
this.setState({ currentTimer: Math.round(time / 1000)});
}, 1000);
}
stopTimer() {
this.setState({ timer: false });
clearInterval(this.timerID);
}
Run Code Online (Sandbox Code Playgroud)
工作代码:
startTimer() {
const start = Date.now();
this.setState({ timer: true });
// storing the id
this.timerID = setInterval(() => {
let time = new Date() - start;
this.setState({ currentTimer: Math.round(time / 1000)});
}, 1000);
}
stopTimer() {
this.setState({ timer: false });
clearInterval(this.timerID);
}
Run Code Online (Sandbox Code Playgroud)
class App extends React.Component {
constructor(){
super();
this.state = {currentTimer: ''}
this.startTimer = this.startTimer.bind(this);
this.stopTimer = this.stopTimer.bind(this);
}
startTimer() {
const start = Date.now();
this.timerID = setInterval(() => {
let time = Math.random() * 10;
this.setState({ currentTimer: time});
}, 1000);
}
stopTimer() {
clearInterval(this.timerID);
}
render(){
return (
<div>
Value: {this.state.currentTimer || '0'}
<br />
<button onClick={this.startTimer}>Start timer</button>
<button onClick={this.stopTimer}>Stop timer</button>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'))Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2193 次 |
| 最近记录: |