当前位置: 首页 > Web前端 > HTML

封装一个倒计时组件!

时间:2023-03-29 11:43:27 HTML

自定义倒计时组件:importReact,{Component}from'react';functionfixedZero(val){返回val*1<10?`0${val}`:val;}constinitTime=props=>{letlastTime=0;让targetTime=0;try{if(Object.prototype.toString.call(props.target)==='[objectDate]'){targetTime=props.target.getTime();}else{targetTime=newDate(props.target).getTime();}}catch(e){thrownewError('无效的目标道具',e);}lastTime=targetTime-newDate().getTime();返回{lastTime:lastTime<0?0:最后一次,};};类CountDown扩展组件{timer=0;间隔=1000;构造函数(道具){超级(道具);const{lastTime}=initTime(props);this.state={lastTime,};}staticgetDerivedStateFromProps(nextProps,preState){const{lastTime}=initTime(nextProps);如果(preState.lastTime!==lastTime){return{lastTime,};}返回空值;}组合nentDidMount(){this.tick();}componentDidUpdate(prevProps){const{target}=this.props;if(target!==prevProps.target){clearTimeout(this.timer);这个.tick();}}componentWillUnmount(){clearTimeout(this.timer);}//defaultFormat=time=>(//{moment(time).format('hh:mm:ss')}//);defaultFormat=time=>{consthours=60*60*1000;常数分钟=60*1000;consth=Math.floor(时间/小时);constm=Math.floor((time-h*hours)/minutes);consts=Math.floor((time-h*hours-m*minutes)/1000);返回({fixedZero(h)}:{fixedZero(m)}:{fixedZero(s)});};tick=()=>{const{onEnd}=this.props;让{lastTime}=this.state;this.timer=setTimeout(()=>{if(lastTime{如果(onEnd){onEnd();}});}else{lastTime-=this.interval;this.setState({lastTime,},()=>{this.tick();});}},这个间隔);};render(){const{format=this.defaultFormat,onEnd,...rest}=this.props;const{lastTime}=this.state;常量结果=格式(上次时间);返回{result};}}导出默认倒计时;使用时直接传入参数即可:{title:'Distanceends',dataIndex:'CreateTime',sorter:true,render:val=>(),//val是倒计时截止日期,最好的格式是YYYY/MM/DDHH:MM:SS}