小编use*_*827的帖子

在 React 中单击按钮停止计时器

我正在开发一个应用程序,并且有一个显示当前日期、小时、分钟和秒的计时器。它每秒递增。我想做的是在单击按钮时停止计时器,但我不确定为什么 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)

javascript timer onclick button reactjs

2
推荐指数
1
解决办法
3393
查看次数

标签 统计

button ×1

javascript ×1

onclick ×1

reactjs ×1

timer ×1