/* * @Author: liqiang * @Date: 2021-02-26 09:38:47 * @LastEditTime: 2021-03-17 16:45:47 * @LastEditors: Please set LastEditors * @Description: 根据传入的毫秒值倒计时 * @FilePath: \ebtp-cloud-frontend\src\pages\Auction\AuctionViewAuctions\components\CountDownUtils.tsx */ import React, { useEffect, useRef, useState } from 'react'; interface CountDownUtilsItem { countDown: number | null, countDownOver: () => void } const sixty = 60; const threeThousandAndSixHundred = 3600; const twentyFour = 24; const hourSeconds = twentyFour * threeThousandAndSixHundred; const ten = 10; const CountDownUtils: React.FC = (props) => { const { countDown, countDownOver } = props; const [time, setTime] = useState(); const ref = useRef(); useEffect(() => { if (countDown === null) { return; } let maxtime = countDown / 1000; //按秒计算 clearInterval(ref.current); const interval = setInterval(() => { // if (maxtime >= 0) { // //计算出相差天数 // let days = Math.floor(maxtime / hourSeconds); // //计算出小时数 // let leave1 = maxtime % hourSeconds; //计算天数后剩余的秒数 // let hours = Math.floor(leave1 / threeThousandAndSixHundred); // //计算相差分钟数 // let leave2 = leave1 % threeThousandAndSixHundred; //计算小时数后剩余的秒数 // let minutes = Math.floor(leave2 / sixty); // //计算相差秒数 // let leave3 = leave2 % sixty; //计算分钟数后剩余的秒数 // let seconds = Math.round(leave3); // setTime(days + '天 ' + hours + '小时 ' + minutes + '分钟 ' + seconds + ' 秒'); // --maxtime; // } else { // clearInterval(interval); // //倒计时结束时,触发父组件的方法 // countDownOver(); // } if (maxtime >= 0) { let ts = maxtime;//计算剩余的毫秒数 let dd = parseInt(String(ts / sixty / sixty / twentyFour), ten);//计算剩余的天数 let hh = parseInt(String(ts / sixty / sixty % twentyFour), ten);//计算剩余的小时数 let mm = parseInt(String(ts / sixty % sixty), ten);//计算剩余的分钟数 let ss = parseInt(String(ts % sixty), ten);//计算剩余的秒数 setTime(dd + '天 ' + hh + '小时 ' + mm + '分钟 ' + ss + ' 秒'); --maxtime; } else { clearInterval(ref.current); //倒计时结束时,触发父组件的方法 countDownOver(); } }, 1000); ref.current = interval; }, [countDown]); return ( <> {time} ) } export default CountDownUtils;