react实现简单倒计时

今天遇到一个简单的小功能,看网上的一些方法感觉不太适合,所以就手敲了一个,直接上代码!!!

 1 import React, { Component } from 'react';
 2 
 3 class NoTimeContent extends Component {
 4     constructor(props) {
 5         super(props)
 6         this.state = {
 7             day: 0,
 8             hour: 0,
 9             minute: 0,
10             second: 0
11         }
12     }
13     render() {
14         return (
15             <NoTimeCon>
16                 <h2>
17                     <span>限时秒杀</span>
18                     <span>{this.state.day}天 {this.state.hour}:{this.state.minute}:{this.state.second}</span>
19                 </h2>
20             </NoTimeCon>
21         )
22     }
23 
24 componentDidMount() {
25       const end = Date.parse(new Date('2018-11-29 24:00'))
26       this.countFun(end);
27     }
28   
29   //卸载组件取消倒计时
30   componentWillUnmount(){
31     clearInterval(this.timer);
32   }
33   
34   countFun = (end) => {
35 
36     let now_time = Date.parse(new Date());
37     var remaining = end - now_time;
38  
39     this.timer = setInterval(() => {
40         //防止出现负数
41       if (remaining > 1000) {
42         remaining -= 1000;
43         let day = Math.floor((remaining / 1000 / 3600) / 24);
44         let hour = Math.floor((remaining / 1000 / 3600) % 24);
45         let minute = Math.floor((remaining / 1000 / 60) % 60);
46         let second = Math.floor(remaining / 1000 % 60);
47 
48         this.setState({
49             day:day,
50             hour:hour < 10 ? "0" + hour : hour,
51             minute:minute < 10 ? "0" + minute : minute,
52             second:second < 10 ? "0" + second : second
53         })
54       } else {
55         clearInterval(this.timer);
56         //倒计时结束时触发父组件的方法
57         //this.props.timeEnd();
58       }
59     }, 1000);
60   }
61 
62 }
63 export default NoTimeContent;

猜你喜欢

转载自www.cnblogs.com/luxiaot/p/10010149.html
今日推荐