react 写 倒计时功能

Posted lxy02

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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() {
        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‘,
                hours: ‘00‘,
                minutes: ‘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, hours,  minutes,  seconds } = this.state;
        return (
            <div className="count-down">
                <span>{day}</span>:
                <span>{hours}</span>:
                <span>{minutes}</span>:
                <span>{seconds}</span>
            </div>
        );
    }
}

实现效果如下:

技术分享图片

 

以上是关于react 写 倒计时功能的主要内容,如果未能解决你的问题,请参考以下文章

计时器60s

react实现简单倒计时

python使用上下文对代码片段进行计时,非装饰器

react 手写优化实现 antd 倒计时功能组件( 附源码)

如何在 React 功能组件中正确设置 setInterval 计时器?

react 手写优化实现 antd 倒计时功能组件( 附源码)