import * as React from 'react'; import { Props, State } from './type'; export default class CountDown extends React.Component { public static defaultProps = new Props(); public state = new State(); public componentWillReceiveProps(props) { this.refresh(props) } public componentDidMount() { this.refresh(this.props) } public refresh(props){ const {startTime, endTime} = props; if(!startTime || !endTime) return; const nowDate = new Date(); const isStart = nowDate >= startTime; const isEnd = nowDate > endTime; this.setState({ isStart, isEnd }) if(isStart && !isEnd){ const refreshTime = () => { let countDown = this.countDown(startTime, endTime) this.setState({ countDown }) } refreshTime() setInterval(()=>refreshTime(), 1000) } } public countDown(startTime, endTime){ let endDate = new Date(endTime); //当前时间 let nowDate = new Date(); if(nowDate > endDate){ return 'end' }else if(nowDate < startTime){ return 'notStart' } //相差的总秒数 let totalSeconds = parseInt((endDate - nowDate) / 1000); //天数 let days = Math.floor(totalSeconds / (60 * 60 * 24)); //取模(余数) let modulo = totalSeconds % (60 * 60 * 24); //小时数 let hours = Math.floor(modulo / (60 * 60)); modulo = modulo % (60 * 60); //分钟 let minutes = Math.floor(modulo / 60); //秒 let seconds = modulo % 60; return{ days, hours, minutes, seconds } } public render() { return (
{ !this.state.isStart ? "敬请期待" : this.state.isEnd ? "活动已结束" :
活动截止倒计时: {this.state.countDown.days}{this.state.countDown.hours}{this.state.countDown.minutes}{this.state.countDown.seconds}
}
) } }