• 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',也不传,默认是展示 分 秒
     
    回调函数也可传可不传,默认不传,可根据实际情况而定。
     
    效果图:
     
    
    
  • 相关阅读:
    List of all Oracle Server Parameters
    dbcc Trace
    站在巨人的肩膀上 书籍推荐 (zz)
    浅谈JS包装对象
    与 JavaScript 模块相关的所有知识点
    你真的懂Promise吗
    vue动态绑定class与style总结
    vue使用axios实现excel文件下载的实现
    CSRF 与 XSS
    推荐10个很棒的 JS 库
  • 原文地址:https://www.cnblogs.com/wyq186/p/9934088.html
Copyright © 2020-2023  润新知