1. 程式人生 > >react實現簡單倒計時

react實現簡單倒計時

port ons cto ear 小功能 extend com 實現 state

今天遇到一個簡單的小功能,看網上的一些方法感覺不太適合,所以就手敲了一個,直接上代碼!!!

 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;

react實現簡單倒計時