封装倒计时组件

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

const CutDown = props => {
  const { shelfTime } = props;//截止时间
  const timer = useRef(0);
  const [remaining, setRemaining] = useState({
    day: 0,
    hour: 0,
    minute: 0,
    second: 0
  });

  const countFun = end => {
    let now_time = Date.parse(new Date());
    var remaining = end - now_time;
    timer.current = setInterval(() => {
      //防止出现负数
      if (remaining > 1000) {
        remaining -= 1000;
        let day = Math.floor(remaining / 1000 / 3600 / 24);
        let hour = Math.floor((remaining / 1000 / 3600) % 24);
        let minute = Math.floor((remaining / 1000 / 60) % 60);
        let second = Math.floor((remaining / 1000) % 60);
        setRemaining({
          day: day,
          hour: hour < 10 ? '0' + hour : hour,
          minute: minute < 10 ? '0' + minute : minute,
          second: second < 10 ? '0' + second : second
        });
      } else {
        clearInterval(timer.current);
        //倒计时结束时触发父组件的方法
        //this.props.timeEnd();
      }
    }, 1000);
  };

  useEffect(() => {
    const end = Date.parse(new Date(shelfTime));
    countFun(end);
  }, []);

  useEffect(() => {
    return () => {
      clearInterval(timer.current);
    };
  }, []);

  return (
    <span>
      {remaining.day}天 { remaining.hour}:{remaining.minute}:{remaining.second}
    </span>
  );
};
export default CutDown;

 

posted @ 2021-07-22 20:05  天官赐福·  阅读(94)  评论(0编辑  收藏  举报
返回顶端