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

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)

wan*_*v87 6

setInterval()结果是intervalID,您应该将其用于clearInterval()

this.state = {
  ...
  intervalId: ""
};

...

const intervalId = setInterval(() => {
   ...
}, 1000);
this.setState({ intervalId });

...

clearInterval(this.state.intervalId);
Run Code Online (Sandbox Code Playgroud)