加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

react实现简单倒计时

发布时间:2020-12-15 20:39:45 所属栏目:百科 来源:网络整理
导读:今天遇到一个简单的小功能,看网上的一些方法感觉不太适合,所以就手敲了一个,直接上代码!!! 1 import React,{ Component } from ‘react‘ ; 2 3 class NoTimeContent extends Component { 4 constructor(props) { 5 super(props) 6 this .state = { 7

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

 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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读