在可视化展示界面时有一种场景,就是页面在初始化的时候,有些数字展示想要从某个值开始动态递增到实际值,形成一种动画效果。例如:

写一个数字递增的组件,有两种方式:1.固定步长,代码如下:
- import {useEffect, useRef, useState} from 'react';
-
- const Counter = ({counts, time = 500}) => { //counts:传入的数字,time: 默认500毫秒之内整个动画完成
- const [count, setCount] = useState(0);
- useEffect(() => {
- const step = counts <= time ? 1 : Math.ceil(counts / time); // 两种情况:1.总数小于time时,就以每毫秒递增1的形式增加;2.总数大于500,计算出每毫秒至少要递增多少
- const timer = setInterval(() => {
- setCount((pre) => (pre + step > counts ? counts : pre + step));
-
- }, 1);
- return () => clearInterval(timer);
- }, [counts]);
- return count;
-
- }
- export default Counter;
2.固定时间,代码如下:
- import {useEffect, useRef, useState} from 'react';
-
- const Counter = ({counts, time = 500}) => { //counts:传入的数字,time: 默认500毫秒之内整个动画完成
- const [count, setCount] = useState(0);
- useEffect(() => {
- let startTime = Date.now();
- let duration = 2000;
- const timer = setInterval(() => {
- setCount(() => {
- //数字增长逻辑:.定时操作
- let after = Math.ceil((Date.now()-startTime)/duration*counts*100)/100;
- if(after > counts) {
- clearInterval(timer);
- after = counts;
- }
- return after;
- });
- }, 16);
- return () => clearInterval(timer);
- }, [counts]);
- return count;
-
- }
- export default Counter;
然后就可以在其他代码中引用该组件了:
Counter counts={500} />
当然,还可以使用react-countup组件 来实现,步骤如下:
在项目中install该组件
npm install react-countup
然后引入即可
import CountUp from "react-countup"; <CountUp start={0} end={100000} duration={3} />上面组件的参数说明:
start: number 开始值end: number 结束值duration: number 动画完成用时,以秒为单位decimals: number 小数位数useEasing: boolean 设置宽松,一般情况是trueuseGrouping: boolean 设置分组功能,设为true才能用千位分割器等功能separator: string 指定千位分隔符的字符,比如说最常见的”,”decimal: string 指定小数字符prefix: string 动画值前缀suffix: string 动画值后缀,可以加单位className: string span元素的CSS类名redraw: boolean 如果设置为true,CountUp组件将始终在每个重新渲染上进行动画处理。onComplete: function 动画完成后调用的函数onStart: function 在动画开始前调用的函数easingFn: function Easing function,一般用不到formattingFn: function 用于自定义数字格式的方法
看一个例子:
- import React from 'react';
- import { render } from 'react-dom';
- import CountUp from 'react-countup';
-
- const onComplete = () => {
- console.log('Completed! ?');
- };
-
- const onStart = () => {
- console.log('Started! ?');
- };
-
- render(
- <CountUp
- className="account-balance"
- start={160527.0127}
- end={-875.0319}
- duration={2.75}
- useEasing={true}
- useGrouping={true}
- separator=" "
- decimals={4}
- decimal=","
- prefix="EUR "
- suffix=" left"
- onComplete={onComplete}
- onStart={onStart}
- />,
- document.getElementById('root'),
- );