index.js 2.29 KB
Newer Older
afc163's avatar
afc163 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
import React, { Component } from 'react';

function fixedZero(val) {
  return val * 1 < 10 ? `0${val}` : val;
}

class CountDown extends Component {
  constructor(props) {
    super(props);

    const { lastTime } = this.initTime(props);

    this.state = {
      lastTime,
    };
  }

  componentDidMount() {
    this.tick();
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.target !== nextProps.target) {
24
      clearTimeout(this.timer);
afc163's avatar
afc163 committed
25 26 27
      const { lastTime } = this.initTime(nextProps);
      this.setState({
        lastTime,
28 29
      }, () => {
        this.tick();
afc163's avatar
afc163 committed
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
      });
    }
  }

  componentWillUnmount() {
    clearTimeout(this.timer);
  }

  timer = 0;
  interval = 1000;
  initTime = (props) => {
    let lastTime = 0;
    let targetTime = 0;
    try {
      if (Object.prototype.toString.call(props.target) === '[object Date]') {
        targetTime = props.target.getTime();
      } else {
        targetTime = new Date(props.target).getTime();
      }
    } catch (e) {
      throw new Error('invalid target prop', e);
    }

    lastTime = targetTime - new Date().getTime();

    return {
      lastTime,
    };
  }
  // defaultFormat = time => (
  //  <span>{moment(time).format('hh:mm:ss')}</span>
  // );
  defaultFormat = (time) => {
    const hours = 60 * 60 * 1000;
    const minutes = 60 * 1000;

    const h = fixedZero(Math.floor(time / hours));
    const m = fixedZero(Math.floor((time - (h * hours)) / minutes));
    const s = fixedZero(Math.floor((time - (h * hours) - (m * minutes)) / 1000));
    return (
      <span>{h}:{m}:{s}</span>
    );
  }
  tick = () => {
    const { onEnd } = this.props;
    let { lastTime } = this.state;

    this.timer = setTimeout(() => {
      if (lastTime < this.interval) {
        clearTimeout(this.timer);
        this.setState({
          lastTime: 0,
82 83 84 85
        }, () => {
          if (onEnd) {
            onEnd();
          }
afc163's avatar
afc163 committed
86 87 88 89 90
        });
      } else {
        lastTime -= this.interval;
        this.setState({
          lastTime,
91 92
        }, () => {
          this.tick();
afc163's avatar
afc163 committed
93 94 95 96 97 98
        });
      }
    }, this.interval);
  }

  render() {
jim's avatar
jim committed
99
    const { format = this.defaultFormat, onEnd, ...rest } = this.props;
afc163's avatar
afc163 committed
100 101 102 103
    const { lastTime } = this.state;

    const result = format(lastTime);

nikogu's avatar
nikogu committed
104
    return (<span {...rest}>{result}</span>);
afc163's avatar
afc163 committed
105 106 107 108
  }
}

export default CountDown;