【发布时间】:2021-03-26 11:12:38
【问题描述】:
我正在开发一个应用程序,我有一个显示当前日期、小时、分钟和秒数的计时器。它每秒递增一次。我想要做的是在单击按钮时停止计时器,但我不确定为什么 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>
)
}
}
【问题讨论】:
-
这能回答你的问题吗? setInterval in a React app
标签: javascript reactjs button timer onclick