react实现倒计时方法

一、后端传参

1、定义一个组件CountDownWapper,存放封装好的时间组件

代码如下:

import { useState, useRef, useEffect } from 'react';

interface TimeViewProps {
  h: string; // 小时
  m: string; // 分钟
  s: string; // 秒
}

type TCountDownWapper = {
  expire: number; //过期时间
  showDomStruct?: boolean;  //是否显示
};

const CountDownWapper: React.FC<TCountDownWapper> = (props) => {
  const countDownTimer = useRef<NodeJS.Timeout>(); // 倒计时标记
  const [timeView, setTimeView] = useState<TimeViewProps | null>(null); // 倒计时显示

  // 倒计时函数
  const countDown = () => {
    const nowTime = +new Date(); //获取當前时间的时间戳(单位毫秒)
    const times = parseInt(`${(props.expire - nowTime) / 1000}`); //把剩余时间毫秒数转化为秒
    const h = parseInt(`${(times / 60 / 60) % 24}`); //计算小时数 转化为整数
    const m = parseInt(`${(times / 60) % 60}`); //计算分钟数 转化为整数
    const s = parseInt(`${times % 60}`); //计算描述 转化为整数

    //设置时间格式
    setTimeView({
      h: h < 10 ? `0${h}` : `${h}`,
      m: m < 10 ? `0${m}` : `${m}`,
      s: s < 10 ? `0${s}` : `${s}`,
    });

    //时间判断
    if (times <= 0) {
      clearTimeout(countDownTimer.current);
      setTimeView({ h: '00', m: '00', s: '00' });
    } else {
      countDownTimer.current = setTimeout(() => {
        countDown();
      }, 1000);
    }
  };

  useEffect(() => {
    if (props.expire) {
      countDown();
    } else {
      setTimeView({ h: '00', m: '00', s: '00' });
    }
    return () => {
      clearTimeout(countDownTimer.current);
    };
  }, []);


  return (
    <>
      {props.showDomStruct ?? true ? (
        <>
          {timeView?.h}:{timeView?.m}:{timeView?.s}
        </>
      ) : (
        <></>
      )}
    </>
  );
};
export default CountDownWapper;

注意:expire过期时间是由后端传过来的!

2、时间组件的使用

01.在页面使用

代码如下:

<div className="countdown">
  剩餘支付時間
  <span className="lastTime">
      <CountDownWapper
       expire={validTime}
       showDomStruct={true}
      />    
  </span>
</div>

02.页面呈现效果

二、前端定义时间

方法代码如下:

const [seconds, setSeconds] = useState(3); //初始定义为3秒钟

//倒计时函数
 const countDown = () => {
    setTimeout(() => {
      setSeconds((data) => {
        if (data == 1) {
          goBack();
        } else {
          countDown();
        }
        return data - 1;
      });
    }, 1000);
  };

useEffect(() => {
  countDown();
}, []);

页面使用:

 <p className={styles['timeout-desc']}>{seconds}s後返回商家</p>

效果如下:

 

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值