效果:
组件:(NumberScroller.jsx)
/*** 数字滚动效果*/ import React, { useEffect, useState } from 'react'; import PropTypes from 'prop-types';const NumberScroller = ({ targetValue = 0, decimalPlaces = 0, duration = 2000 }) => {const [value, setValue] = useState(0);useEffect(() => {const start = performance.now();const interval = setInterval(() => {const elapsed = performance.now() - start;const progress = elapsed / duration;const newValue = value + (targetValue - value) * progress;setValue(newValue);if (progress >= 1) {clearInterval(interval);setValue(targetValue);}}, 10);return () => clearInterval(interval);}, [targetValue, duration]);return <div style={{ fontSize: 80 }}>{value.toFixed(decimalPlaces)}</div>; };NumberScroller.propTypes = {// 目标值targetValue: PropTypes.number,// 保留多少位小数decimalPlaces: PropTypes.number,// 滚动速率(数字越大,滚动越慢)duration: PropTypes.number, };export default NumberScroller;
测试:
import { useEffect, useState } from 'react';import NumberScroller from './NumberScroller';const Page = () => {const [targetValue, setTargetValue] = useState(Math.random() * 2000);useEffect(() => {}, []);return (<div className="test" style={{ padding: 20 }}><NumberScroller targetValue={targetValue} /><buttononClick={() => {setTargetValue(Math.random() * 2000);}}>更改</button></div>); };export default Page;