use*_*827 2 javascript timer onclick button reactjs
我正在开发一个应用程序,并且有一个显示当前日期、小时、分钟和秒的计时器。它每秒递增。我想做的是在单击按钮时停止计时器,但我不确定为什么 clearInterval() 函数不起作用。我的代码是:
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = {
timer: "",
};
}
componentDidMount() {
//current time
setInterval(() => {
this.setState({
currentTime : new Date().toLocaleString()
})
}, 1000)
}
stopTimer = () => {
clearInterval(this.state.currentTime)
}
render() {
return (
<div>
<h4>Current time: {this.state.currentTime}</h4>
<Button onClick={this.stopTimer}>Stop timer</Button>
</div>
)
}
}
Run Code Online (Sandbox Code Playgroud)
setInterval()结果是intervalID,您应该将其用于clearInterval()。
this.state = {
...
intervalId: ""
};
...
const intervalId = setInterval(() => {
...
}, 1000);
this.setState({ intervalId });
...
clearInterval(this.state.intervalId);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3393 次 |
| 最近记录: |