react倒计时

2021-04-13  本文已影响0人  金药
import React, { Component } from 'react'

interface Props {
  endTime: string;
  endTimeFun?: Function;
}
interface State {
  day: string | number;
  hour: string | number;
  minute: string | number;
  second: string | number;
}
export default class CountDown extends Component<Props, State> {
  timer: NodeJS.Timeout;
  constructor(props) {
    super(props);
    this.state = {
      day: 0,
      hour: 0,
      minute: 0,
      second: 0
    }
  }
  componentDidMount() {
    if (this.props.endTime) {
      let endTime = this.props.endTime.replace(/-/g, "/");
      this.countFun(endTime);
    }
  }

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

  countFun = (time) => {
    let end_time = new Date(time).getTime(),
      sys_second = end_time - new Date().getTime();

    // 将倒计时方法抽出,立即触发第一次倒计时
    const startTimer = () => {
      //防止倒计时出现负数
      if (sys_second > 1000) {
        sys_second -= 1000;
        let day = Math.floor((sys_second / 1000 / 3600) / 24);
        let hour = Math.floor((sys_second / 1000 / 3600) % 24);
        let minute = Math.floor((sys_second / 1000 / 60) % 60);
        let second = Math.floor(sys_second / 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.endTimeFun && this.props.endTimeFun();
      }
      return startTimer
    }

    this.timer = setInterval(startTimer(), 1000);
  }

  render() {
    const { day, hour, minute, second } = this.state;
    return (
      <>
        {day ? `${day}天` : ''}
        {hour && hour !== '00' ? `${hour}:` : ''}
        {minute == '0' ? '00' : minute}:
        {second == '0' ? '00' : second}
      </>
    )
  }
}

引用

<CountDown endTime={‘2021-04-14 15:56:08’} endTimeFun={endTimeFun} />
上一篇下一篇

猜你喜欢

热点阅读