react-app-shell
Version:
react打包脚本和example, 这里的版本请忽略
146 lines (124 loc) • 3.83 kB
JavaScript
import React, {PureComponent} from 'react';
import propTypes from 'prop-types';
import moment from 'moment';
import styles from '../styles.less';
/**
* 倒计时
*/
export default class CountDown extends PureComponent {
static propTypes = {
finishCallback: propTypes.func, // 倒计时结束时的回调
};
static defaultProps = {
endTime: 0,
serverTime: 0,
finishCallback: () => {
},
};
state = {
endTime: this.props.endTime,
serverTime: this.props.serverTime,
count: 0,
ms: 10,
};
componentDidMount() {
this.startCountDown(this.state.endTime, this.state.serverTime);
}
componentWillReceiveProps(nextProps) {
if (nextProps.endTime !== this.state.endTime || nextProps.serverTime !== this.state.serverTime) {
this.startCountDown(nextProps.endTime, nextProps.serverTime);
}
}
componentWillUnmount() {
/**
* 组件销毁 清除定时器
*/
clearInterval(this.timer);
}
timer = null;
startCountDown = (endTime, nowTime) => {
let count = 0;
// 如果活动结束时间为真, 并且大于当前时间, 则记录倒计时毫秒数
if (endTime && endTime > nowTime) {
count = (moment(endTime).format('X') - moment(nowTime).format('X')) * 1000;
}
this.setState({
endTime,
count,
serverTime: nowTime,
});
clearInterval(this.timer);
if (count === 0) {
return;
}
this.timer = setInterval(() => {
let {count, ms} = this.state;
if (ms === 0) {
ms = 10;
}
if (count) {
count = count - 100;
ms = Number(ms) - 1;
}
if (count && count < 0 || count === 0) {
count = 0;
clearInterval(this.timer);
// 倒计时结束时回调
this.props.finishCallback && this.props.finishCallback();
}
this.setState({
count,
ms
});
}, 100);
};
/**
* 格式化时间
*/
getFormatTime = (count) => {
let day = parseInt(count / (24 * 60 * 60 * 1000), 10);
let hours = parseInt((count / 60 / 60 / 1000) % 24, 10);
let minute = parseInt((count / 60 / 1000) % 60, 10);
let second = parseInt((count / 1000) % 60, 10);
return {
day,
hours,
minute,
second,
};
};
/**
* 将0-9的数字前面加上0,例1变为01
*/
checkTime = (i) => {
if (isNaN(i)) {
return '00';
}
if (i < 10) {
i = '0' + i;
}
return i;
};
render() {
let {count, ms} = this.state;
const {day, hours, minute, second} = this.getFormatTime(count);
return (
<div>
<div className={styles['innercon']}>
<div className={styles['count-title']}>
<div className={styles['count-hr']}/>
<span>活动倒计时</span>
<div className={styles['count-hr']}/>
</div>
<div className={styles['time']}>
<span>{this.checkTime(day)}</span>天
<span>{this.checkTime(hours)}</span>时
<span>{this.checkTime(minute)}</span>分
<span>{this.checkTime(second)}</span>秒
<span>{this.checkTime(ms)}</span>
</div>
</div>
</div>
);
}
}