組件的實現
import React, {Component} from 'react'
export default class CountTimeDown extends Component {
constructor(props) {
super(props);
this.state = {
day: 0,
hour: 0,
minute: 0,
second: 0
}
}
componentDidMount() {
if (this.props.endTime) {
let endTime = this.props.endTime.replace(/-/g, "/");
this.countFun(endTime);
}
}
//組件卸載取消倒計時
componentWillUnmount() {
clearInterval(this.timer);
}
countFun = (time) => {
let end_time = new Date(time).getTime(),
sys_second = (end_time - new Date().getTime());
this.timer = setInterval(() => {
//防止倒計時出現負數
if (sys_second > 1000) {
sys_second -= 1000;
let day = Math.floor((sys_second / 1000 / 3600) / 24);
let hour = Math.floor((sys_second / 1000 / 3600) % 24);
let minute = Math.floor((sys_second / 1000 / 60) % 60);
let second = Math.floor(sys_second / 1000 % 60);
this.setState({
day: day,
hour: hour < 10 ? "0" + hour : hour,
minute: minute < 10 ? "0" + minute : minute,
second: second < 10 ? "0" + second : second
})
} else {
clearInterval(this.timer);
}
}, 1000);
};
render() {
return (
<span>{this.state.minute}分{this.state.second}秒</span>
)
}
}
使用組件
/**
* 倒計時實現
* @constructor
*/
Minutes = () => {
let date = new Date();
let min = date.getMinutes();
date.setMinutes(min + 30);
let newdate = date.toLocaleString('chinese', {hour12: false}); //獲取24小時制,中國時間,打印出 2019/01/03/ 08:40:32
console.log(newdate);
this.setState({
date: newdate,
});
};
<CountDown endTime={this.state.date}/>