react-app-shell
Version:
react打包脚本和example, 这里的版本请忽略
123 lines (104 loc) • 3.37 kB
JavaScript
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import styles from './count-down.less';
class CountDown extends Component {
static propTypes = {
endTime: PropTypes.number.isRequired, // 活动开始时间
serverTime: PropTypes.number.isRequired, // 服务器时间
completeCallback: PropTypes.func, // 倒计时结束
};
static defaultProps = {
endTime: 0,
serverTime: 0,
};
state = {
endTime: this.props.endTime,
serverTime: this.props.serverTime,
completeCallback: this.props.completeCallback,
count: 0, // 倒计时毫秒数
isEnd: false
};
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 = endTime - nowTime;
}
this.setState({
endTime,
count,
serverTime: nowTime,
});
clearInterval(this.timer);
if (count === 0) {
return;
}
this.timer = setInterval(() => {
let {count, completeCallback} = this.state;
if (count) {
count = count - 1000;
}
if (count && count < 0 || count === 0) {
count = 0;
clearInterval(this.timer);
// 倒计时结束
completeCallback && completeCallback();
}
this.setState({
count,
});
}, 1000);
};
/**
* 格式化时间
*/
getFormatTime = (count) => {
count = count / 1000;
let day = parseInt(count / 60 / 60 / 24, 10);
let hours = parseInt((count / 60 / 60) % 24, 10);
let minute = parseInt((count / 60) % 60, 10);
let second = parseInt(count % 60, 10);
day = day < 10 ? `0${day}` : day;
hours = hours < 10 ? `0${hours}` : hours;
minute = minute < 10 ? `0${minute}` : minute;
second = second < 10 ? `0${second}` : second;
return {
day,
hours,
minute,
second
};
};
render() {
let {count} = this.state;
const {day, hours, minute, second} = this.getFormatTime(count);
return (
<div className={styles['countdown']}>
<div className={styles['innercon']}>
<div className={styles['time']}>
<span>{day}</span>天
<span>{hours}</span>时
<span>{minute}</span>分
<span>{second}</span>秒
</div>
</div>
</div>
);
}
}
export default CountDown;