zoukankan      html  css  js  c++  java
  • 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',也不传,默认是展示 分 秒
     
    回调函数也可传可不传,默认不传,可根据实际情况而定。
     
    效果图:
     
    
    
  • 相关阅读:
    SpringMvc执行流程
    Lock wait timeout exceeded; try restarting transaction解决方法
    MySQL删除复杂的重复数据的解决方案(一条数据项中包含多个值的情况)
    数据移植时递归运算查询部门及其下级所有部门的问题
    IDEA常用插件
    mybatis和mybatisPlus中解决实体类字段与数据库关键字冲突问题
    时间日期操作
    spring项目中使用MD5加密方式
    idea如何调出仪表盘
    scanf使用过程中的技巧与坑位
  • 原文地址:https://www.cnblogs.com/wyq186/p/9934088.html
Copyright © 2011-2022 走看看