react-app-shell
Version:
react打包脚本和example, 这里的版本请忽略
132 lines (120 loc) • 4.06 kB
JavaScript
// 功能方法>>>引用:
import React, {Component} from 'react';
import propTypes from 'prop-types';
import classNames from 'classnames';
// 枚举>>>引用:
import {LANDING_ACTIVITY_STATUS} from '../../constants/landing';
// 样式>>>引用:
import styles from './landing.less';
export default class CountDown extends Component {
/**
* 倒计时完成 指定回调类型
*/
static propTypes = {
onFinish: propTypes.func,
};
/**
* 倒计时完成 默认回调
*/
static defaultProps = {
onFinish: () => {
},
};
/**
* 数据
*/
state = {
time: 0,
};
/**
* 加载完成钩子
*/
componentDidMount() {
const {countDownTime, nowTime} = this.props;
this.countDownBegin(countDownTime, nowTime);
}
/**
* 开启定时器
* @param
* @countDownTime 倒计时时间
* @nowTime 服务器返回现在时间
*/
countDownBegin = (countDownTime, nowTime) => {
const {configId, onFinish, activeState} = this.props;
this.timer && clearInterval(this.timer);
let timerValue = countDownTime - nowTime;
if (!countDownTime) return;
if (timerValue <= 0) return;
if (activeState === LANDING_ACTIVITY_STATUS.ACTIVITY_END) { // 活动已结束: 关闭倒计时时间初始化
timerValue = 0;
return;
}
this.setState({
time: timerValue
});
this.timer = setInterval(() => {
let {time} = this.state;
if (time <= 0) { // 倒计时走完调用回调函数
onFinish && onFinish(configId);
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() {
let {time} = this.state;
let countDownTime = this.formatTime(time);
let {activeState} = this.props;
// 活动未开始: 关闭倒计时显示文字
let clgTimeClass = (activeState === LANDING_ACTIVITY_STATUS.ACTIVITY_NOT_START) ? true : false;
return (
<React.Fragment>
<div className={styles.clgTime}>
<p className={styles.title}>限时秒杀倒计时</p>
<span className={classNames(styles.clgTimeBlock, {
[styles.clgNone]: clgTimeClass
})}>
<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>
<p className={classNames(styles.notStart, {
[styles.clgNone]: !clgTimeClass
})}>活动未开始</p>
</div>
</React.Fragment>
);
}
}