小编典典

React中的倒数计时器

reactjs

我已经在JavaScript中看到了许多倒数计时器,并希望在React中使用它。

我借用了我在网上找到的此功能:

secondsToTime(secs){
    let hours = Math.floor(secs / (60 * 60));

    let divisor_for_minutes = secs % (60 * 60);
    let minutes = Math.floor(divisor_for_minutes / 60);

    let divisor_for_seconds = divisor_for_minutes % 60;
    let seconds = Math.ceil(divisor_for_seconds);

    let obj = {
        "h": hours,
        "m": minutes,
        "s": seconds
    };
    return obj;
  };

然后我自己写了这段代码

  initiateTimer = () => {
    let timeLeftVar = this.secondsToTime(60);
    this.setState({ timeLeft: timeLeftVar })
  };

  startTimer = () => {
    let interval = setInterval(this.timer, 1000);
    this.setState({ interval: interval });
  };

  timer = () => {
    if (this.state.timeLeft >0){
      this.setState({ timeLeft: this.state.timeLeft -1 });
    }
    else {
      clearInterval(this.state.interval);
      //this.postToSlack();
    }
  };

当前onclick会将其在屏幕上的时间设置为:Time Remaining: 1 m : 0 s 但不会将其减少到Time Remaining: 0 m : 59 s,然后Time Remaining: 0 m : 58 s等等等

我想我需要使用其他参数再次调用该函数。我该怎么做呢?

编辑:我忘了说,我想要功能,这样我就可以使用秒到分钟和秒


阅读 399

收藏
2020-07-22

共1个答案

小编典典

您必须setState每秒剩余几秒钟(每次调用间隔)。这是一个例子:

class Example extends React.Component {

  constructor() {

    super();

    this.state = { time: {}, seconds: 5 };

    this.timer = 0;

    this.startTimer = this.startTimer.bind(this);

    this.countDown = this.countDown.bind(this);

  }



  secondsToTime(secs){

    let hours = Math.floor(secs / (60 * 60));



    let divisor_for_minutes = secs % (60 * 60);

    let minutes = Math.floor(divisor_for_minutes / 60);



    let divisor_for_seconds = divisor_for_minutes % 60;

    let seconds = Math.ceil(divisor_for_seconds);



    let obj = {

      "h": hours,

      "m": minutes,

      "s": seconds

    };

    return obj;

  }



  componentDidMount() {

    let timeLeftVar = this.secondsToTime(this.state.seconds);

    this.setState({ time: timeLeftVar });

  }



  startTimer() {

    if (this.timer == 0 && this.state.seconds > 0) {

      this.timer = setInterval(this.countDown, 1000);

    }

  }



  countDown() {

    // Remove one second, set state so a re-render happens.

    let seconds = this.state.seconds - 1;

    this.setState({

      time: this.secondsToTime(seconds),

      seconds: seconds,

    });



    // Check if we're at zero.

    if (seconds == 0) {

      clearInterval(this.timer);

    }

  }



  render() {

    return(

      <div>

        <button onClick={this.startTimer}>Start</button>

        m: {this.state.time.m} s: {this.state.time.s}

      </div>

    );

  }

}



ReactDOM.render(<Example/>, document.getElementById('View'));


<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="View"></div>
2020-07-22