react 写 倒计时

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

// 倒计时

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() {
        this.time && clearTimeout(this.time);
    }

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

    _formatTime = (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, hours,  minutes,  seconds } = this.state;
        return (
            <div className="count-down">
                <span>{day}</span>:
                <span>{hours}</span>:
                <span>{minutes}</span>:
                <span>{seconds}</span>
            </div>
        );
    }
}

实现效果如下:

 

转载于:https://www.cnblogs.com/LXY02/p/9351201.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值