react 倒计时 countDown

 
 

因为项目需要做一个react倒计时组件,网络上也有,但是感觉不是很好,兼容性不高,于是自己写了一个:

 
 

1.包含 天,时,分,秒。可以根据特定的场景选择相应的展示方式;

 
 

2.提供回调函数。


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


父组件:

  <CountDown endTime="2018/11/10 17:10:00" type='day' timeOver={()=>this.timeOver()}/>
 
type 可以传'day'和'hour',也不传,默认是展示 分 秒
 
回调函数也可传可不传,默认不传,可根据实际情况而定。
 
效果图:
 
 

猜你喜欢

转载自www.cnblogs.com/wyq186/p/9934088.html
今日推荐