react-app-shell
Version:
react打包脚本和example, 这里的版本请忽略
125 lines (113 loc) • 3.15 kB
JavaScript
// 功能方法>>>引用:
import React, { Component } from 'react';
import propTypes from 'prop-types';
import classNames from 'classnames';
// 枚举>>>引用:
import { PROCESS_STATUS } from '../../../constants';
// 样式>>>引用:
import styles from '../rabbit.less';
/**
* 魔小兔-倒计时组件
*/
export default class CountDown extends Component {
/**
* 倒计时完成 指定回调类型
*/
static propTypes = {
onFinish: propTypes.func
};
/**
* 倒计时完成 默认回调
*/
static defaultProps = {
onFinish: () => {}
};
/**
* 数据
*/
state = {
time: 0
};
componentDidUpdate(prevProps) {
const { countDownTime: nextCountDownTime } = prevProps;
const { countDownTime, nowTime } = this.props;
if (nextCountDownTime !== countDownTime) {
// 执行定时器
this.countDownBegin(countDownTime, nowTime);
}
}
/**
* 开启定时器
* @countDownTime 倒计时时间
* @nowTime 服务器返回现在时间
*/
countDownBegin = (countDownTime, nowTime) => {
const { id, onFinish } = this.props;
this.timer && clearInterval(this.timer);
if (!countDownTime) return;
const timerValue = countDownTime - nowTime;
if (timerValue <= 0) return;
this.setState({
time: timerValue
});
this.timer = setInterval(() => {
let { time } = this.state;
if (time <= 0) {
// 倒计时走完调用回调函数
onFinish && onFinish(id);
clearInterval(this.timer);
this.timer = null;
return;
}
time = time - 1000;
if (time <= 0) {
time = 0;
}
this.setState({
time
});
}, 1000);
};
/**
* 格式化时间
* @time 时间
*/
formatTime(time) {
let day = Math.floor(time / 1000 / 86400);
day = day < 10 ? '0' + day : day;
let hour = Math.floor(time / 3600000) % 24;
hour = hour < 10 ? '0' + hour : hour;
let minute = Math.floor(time / 60000) % 60;
minute = minute < 10 ? '0' + minute : minute;
let second = Math.floor(time / 1000) % 60;
second = second < 10 ? '0' + second : second;
return {
day,
hour,
minute,
second
};
}
render() {
const { processStatus } = this.props;
if (processStatus === PROCESS_STATUS.ACTIVITY_NOT_START) {
return null;
}
const { time } = this.state;
const countDownTime = this.formatTime(time);
return (
<div className={styles.clgTime}>
<span className={classNames(styles.clgTimeBlock)}>
<span className={styles.clgBlockBig}>{countDownTime.day}</span>
<span className={styles.clgBlockSmall}>天</span>
<span className={styles.clgBlockBig}>{countDownTime.hour}</span>
<span className={styles.clgBlockSmall}>时</span>
<span className={styles.clgBlockBig}>{countDownTime.minute}</span>
<span className={styles.clgBlockSmall}>分</span>
<span className={styles.clgBlockBig}>{countDownTime.second}</span>
<span className={styles.clgBlockSmall}>秒</span>
</span>
</div>
);
}
}