码迷,mamicode.com
首页 > 其他好文 > 详细

react 写 倒计时功能

时间:2018-07-22 20:45:56      阅读:1542      评论:0      收藏:0      [点我收藏+]

标签:classname   one   src   cti   分享   img   分享图片   const   format   

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

// 倒计时

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 写 倒计时功能

标签:classname   one   src   cti   分享   img   分享图片   const   format   

原文地址:https://www.cnblogs.com/LXY02/p/9351201.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!