react倒计时组件(团购中使用:有团购开始时间和团购结束时间)

464 阅读1分钟

直接贴代码

import React, { Component } from "react";

class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      day: 0,
      hour: 0,
      minute: 0,
      second: 0,
    };
  }

  componentDidMount() {
    // 传入的时间格式为“YYYY-MM-DD hh:mm:ss” ,在iPhone打开时需要将“-”转为“/”
    let startDate = Date.parse(this.props.start.replace(/-/g, "/"));
    let endDate = Date.parse(this.props.end.replace(/-/g, "/"));
    this.countFun(startDate, endDate);
  }

  //卸载组件取消倒计时
  componentWillUnmount() {
    clearInterval(this.timer);
  }

  countFun = (start, end) => {
    let now_time = Date.parse(new Date());
    let remaining = 0;
    // console.log(start, end);
    if (now_time > start && now_time < end) {
      // 当前时间可以参与团购
      remaining = end - now_time;
    } else {
      // 当前时间还没有开始参与团购或团购已经结束了
      remaining = 0;
    }

    this.timer = setInterval(() => {
      //防止出现负数
      if (remaining > 1000) {
        remaining -= 1000;
        let day = Math.floor(remaining / 1000 / 3600 / 24);
        let hour = Math.floor((remaining / 1000 / 3600) % 24);
        let minute = Math.floor((remaining / 1000 / 60) % 60);
        let second = Math.floor((remaining / 1000) % 60);
        this.setState({
          day: day,
          hour: hour < 10 ? "0" + hour : hour,
          minute: minute < 10 ? "0" + minute : minute,
          second: second < 10 ? "0" + second : second,
        });
      } else {
        clearInterval(this.timer);
        //倒计时结束时触发父组件的方法
        //this.props.timeEnd();
      }
    }, 1000);
  };

  render() {
    return (
      <div>
        {this.state.day}天{this.state.hour}:{this.state.minute}:
        {this.state.second}
      </div>
    );
  }
}

export default Index;