【问题标题】:Start the timer when button is clicked in React.Js在 React.Js 中单击按钮时启动计时器
【发布时间】:2019-01-29 09:54:51
【问题描述】:

你是如何做到的,这样每当你点击开始按钮时,计时器才会开始。因为现在,它可以随意开始。

class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = { seconds: 0 };
  }

  tick() {
    this.setState(prevState => ({
      seconds: prevState.seconds + 1
    }));
  }

  componentDidMount() {
    this.interval = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  render() {
    return (
      <div>
        Seconds: {this.state.seconds}
        <br />
        <button onClick={this.tick}> Start </button>
      </div>
    );
  }
}

ReactDOM.render(<Timer />, mountNode);

我应该在 onClick 属性中添加什么?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您需要在构造函数中将“tick”绑定到组件,并将用于启动计时器的代码从“componentDidMount”移动到“tick”,如下所示:

    class Timer extends React.Component {
      constructor(props) {
        super(props);
        this.state = { seconds: 0 };
        this.tick = this.tick.bind(this); // bind to the component
      }
    
      tick() {
        // start timer after button is clicked
        this.interval = setInterval(() => {
          this.setState(prevState => ({
            seconds: prevState.seconds + 1
          }));
        }, 1000);
      }
    
      componentWillUnmount() {
        clearInterval(this.interval);
      }
    
      render() {
        return (
          <div>
            Seconds: {this.state.seconds}
            <br />
            <button onClick={this.tick}> Start </button>
          </div>
        );
      }
    }
    
    ReactDOM.render(<Timer />, mountNode);
    

    希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      这就是我们可以使用 React Hooks 实现相同目标的方法。

      const Timer = () => {
        const [isActive, setIsActive] = useState(false);
        const [seconds, setSeconds] = useState(0);
        useEffect(() => {
          let timer = null;
          if(isActive){
            timer = setInterval(() => {
              setSeconds((seconds) => seconds + 1);
            }, 1000);
          }
          return () => {
            clearInterval(timer);
          };
        });
        return (
          <div>
            Seconds: {seconds}
            <br />
            <button onClick={()=>{
              setIsActive(true);
            }}> Start </button>
          </div>
        );
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-20
        • 2019-07-06
        • 2021-03-26
        相关资源
        最近更新 更多