# 数字自增的动画

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

const AnimateCount = ({ time, status = false, number, text = '', step = 10 }) => {
  const [currentNum, setCurrentNum] = useState(0);
  const countRef = useRef(0);
  const initialRef = useRef(0);
  let timer = null;

  useEffect(() => {
    if (status) {
      animationNum();
    }
    return () => {
      timer && clearInterval(timer);
    };
  }, [status]);

  const animationNum = () => {
    if (!isNumber(number)) {
      return;
    }

    const stepNum = number / (time / step);

    if (initialRef.current === number) {
      return;
    }
    timer = setInterval(() => {
      countRef.current = countRef.current + stepNum;
      if (countRef.current >= number) {
        clearInterval(timer);
        countRef.current = number;
      }
      const countNum = Math.floor(countRef.current);
      if (countNum == initialRef.current) {
        return;
      }
      initialRef.current = countNum;
      setCurrentNum(initialRef.current);
    }, 30);
  };

  return (
    <>
      {status && (
        <span>
          {currentNum}
          {text}
        </span>
      )}
    </>
  );
};

export default AnimateCount;

上次更新: 11/8/2024, 10:19:43 AM