React年月日时分秒倒计时实现
  ttOzQgS7km1w 2023年12月12日 28 0


 组件的实现

import React, {Component} from 'react'

export default class CountTimeDown extends Component {
  constructor(props) {
    super(props);
    this.state = {
      day: 0,
      hour: 0,
      minute: 0,
      second: 0
    }
  }

  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);
      }
    }, 1000);
  };

  render() {
    return (
      <span>{this.state.minute}分{this.state.second}秒</span>
    )
  }
}

使用组件

/**
   * 倒计时实现
   * @constructor
   */
  Minutes = () => {
    let date = new Date();
    let min = date.getMinutes();
    date.setMinutes(min + 30);
    let newdate = date.toLocaleString('chinese', {hour12: false});   //获取24小时制,中国时间,打印出   2019/01/03/  08:40:32
    console.log(newdate);
    this.setState({
      date: newdate,
    });
  };
<CountDown endTime={this.state.date}/>

 

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年12月12日 0

暂无评论

推荐阅读
  1BnnW8rtw7M9   2023年12月22日   120   0   0 算法i++i++mathMath算法
ttOzQgS7km1w