加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

react 写 倒计时功能

发布时间:2020-12-15 20:26:55 所属栏目:百科 来源:网络整理
导读:话不多说,代码如下(样式就不贴了,大家都懂的): // 倒计时 import React,{ Component } from ‘react‘ ;import PropTypes from ‘prop-types‘ ;export default class CountDown extends Component { static propTypes = { deadline: PropTypes.number.

话不多说,代码如下(样式就不贴了,大家都懂的):

// 倒计时

import React,{ Component } from ‘react‘;
import PropTypes from ‘prop-types‘;

export default class CountDown extends Component {
    static propTypes = {
        deadline: PropTypes.number.isRequired
    }
    constructor(props) {
        super(props);
        this.state = {
            day: ‘00‘,hours: ‘00‘,minutes: ‘00‘,seconds: ‘00‘
            // milliseconds: ‘00‘
        }
    }

    componentDidMount() {
        this._countDown();
    }

    componentWillUnmount() {
        clearTimeout(this.time);
    }

    _countDown: Function = () => {
        const currTime = new Date().getTime();
        const deadline = this.props.deadline;
        const dTime = deadline - currTime;
        if (dTime <= 0) {
            // 这样做更精确
            clearTimeout(this.time);
            this.setState({
                day: ‘00‘,seconds: ‘00‘
            });
            return;
        }
        this.time = setTimeout(() => {
            this.setState(this._formatTime(dTime));
            this._countDown();
        },1000);
    }

    _formatTime: Function = (time) => {
        const day = Math.floor(time / (1000 * 60 * 60 * 24)).toString().padStart(2,‘0‘);
        const hours = Math.floor(( time / (1000 * 60 * 60)) % 24).toString().padStart(2,‘0‘);
        const minutes = Math.floor(( time / (1000 * 60)) % 60).toString().padStart(2,‘0‘);
        const seconds = Math.floor(( time / 1000) % 60).toString().padStart(2,‘0‘);
        // const milliseconds = Math.floor(time % 1000);
        return ({day,hours,minutes,seconds });
    }
    render() {
        const { day,seconds } = this.state;
        return (
            <div className="count-down">
                <span>{day}</span>:
                <span>{hours}</span>:
                <span>{minutes}</span>:
                <span>{seconds}</span>
            </div>
        );
    }
}

实现效果如下:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读