我是React的新手,我正在尝试创建一个带有启动和停止按钮的简单秒表.我正在撞墙,试图通过"停止"按钮上的onClick事件来清除InterInterval.我会为setInterval声明一个变量,然后使用clearInterval清除它.不幸的是它不起作用.有小费吗?先感谢您.
import React, { Component } from 'react';
class App extends Component {
constructor(props){
super(props);
this.state = {time:0}
this.startHandler = this.startHandler.bind(this);
}
getSeconds(time){
return `0${time%60}`.slice(-2);
}
getMinutes(time){
return Math.floor(time/60);
}
startHandler() {
setInterval(()=>{
this.setState({time:this.state.time + 1});
},1000)
}
stopHandler() {
//HOW TO CLEAR INTERVAL HERE????
}
render () {
return (
<div>
<h1>{this.getMinutes(this.state.time)}:{this.getSeconds(this.state.time)}</h1>
<button onClick = {this.startHandler}>START</button>
<button onClick = {this.stopHandler}>STOP</button>
<button>RESET</button>
</div>
);
}
}
export default App;
Run Code Online (Sandbox Code Playgroud)