react 倒计时 countDown
生活随笔
收集整理的這篇文章主要介紹了
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',也不傳,默認是展示 分 秒 回調函數也可傳可不傳,默認不傳,可根據實際情況而定。 效果圖:?
?
轉載于:https://www.cnblogs.com/wyq186/p/9934088.html
總結
以上是生活随笔為你收集整理的react 倒计时 countDown的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 句子相似度比较的归一化
- 下一篇: eclipse 保存html 提示 sa