组件代码
import React, { useState, useEffect } from 'react'
const Index = (props: any) => {
let timer: any
const [countDown, setCountDown] = useState<any>({ 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 (
<div>
{props.type == 'day' && <span>{countDown.day}天{countDown.hour}:</span>}
{props.type == 'hour' && <span>{countDown.hour}:</span>}{countDown.minute}:{countDown.second}
</div>
)
}
export default Index
// 页面引用
import React, { FC, useState, useEffect, Fragment } from "react";
import CountDown from "./countDown"
const Index = (props: any) => {
return (
// endTime 目标结束时间 type=hour只显示时/分/秒 day显示天/时/分/秒
<CountDowns endTime="2023/3/2 10:21:00" type='hour'/>
)
}
export default Index