React-Hooks倒计时

组件代码

import React, { useState, useEffect } from 'react'

const Index = (props: any) => {
    let timer: any
    const [countDown, setCountDown] = useState({ day: 0, hour: '00', minute: '00', second: '00' })
    const countFun = (time: any) => {
        let end_time = new Date(time).getTime()
        let sys_second = (end_time - new Date().getTime());
        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);
                setCountDown({ day: day, hour: hour < 10 ? "0" + hour : hour, minute: minute < 10 ? "0" + minute : minute, second: second < 10 ? "0" + second : second })
            } else {
                clearInterval(timer);
            }
        }, 1000);
    }
    useEffect(() => {
        if (props.endTime) {
            let endTime = props.endTime.replace(/-/g, "/");
            countFun(endTime);
        }
        return () => {
            clearInterval(timer);
        }
    }, [])
    return (
        
{props.type == 'day' && {countDown.day}天{countDown.hour}:} {props.type == 'hour' && {countDown.hour}:}{countDown.minute}:{countDown.second}
) } export default Index
// 页面引用
import React, { FC, useState, useEffect, Fragment } from "react";
import CountDown from "./countDown"
const Index = (props: any) => {
  return (
      // endTime 目标结束时间  type=hour只显示时/分/秒  day显示天/时/分/秒
      
   )
}
export default Index

你可能感兴趣的:(React-Hooks倒计时)