react 倒計時 countDown


 
        

因為項目需要做一個react倒計時組件,網絡上也有,但是感覺不是很好,兼容性不高,於是自己寫了一個:

 
        

1.包含 天,時,分,秒。可以根據特定的場景選擇相應的展示方式;

 
        

2.提供回調函數。


import React from 'react' export class CountDown extends React.Component { constructor(props) { super(props); this.state = { day: 0, hour: 0, minute: '00', second: '00' } } 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); //倒計時結束時,觸發父組件的方法 if(this.props.timeOver){ this.props.timeOver() } } }, 1000); } render() { return ( <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> ) } }


父組件:

  <CountDown endTime="2018/11/10 17:10:00" type='day' timeOver={()=>this.timeOver()}/>
 
type 可以傳'day'和'hour',也不傳,默認是展示 分 秒
 
回調函數也可傳可不傳,默認不傳,可根據實際情況而定。
 
效果圖:
 

 

 
       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM