最终实现效果
1.安装react-countup
npm install react-countup
2.新建CountTo组件
import React, { useState, useEffect } from 'react';
import CountUp from 'react-countup';
import styles from './index.less';
/**
* 大屏数字滚动组件
*/
class CountToType {
value: number; /**滚动的数字值 */
[p: string]: any;
}
const CountTo: React.FC<CountToType> = props => {
const {value } = props;
const [data, setData] = useState<any[]>([]);
useEffect(() => {
const formattedCountValue = `${value.toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ',')}`; //金额格式化
const str = formattedCountValue.toString();
const arr = str.split('');
setData(arr);
}, [value]);
return (
<>
<div className={styles.countToBox}>
<div className={styles.countToMain}>
{data.map((item: any, index: number) => {
if (item === ',') {
return (
<span className={styles.countToSplit} key={item} style={countConfig.style}>
{item}
</span>
);
} else {
return (
<CountUp
className={styles.countToSumNum}
key={item + '-' + index}
style={countConfig.style}
start={0}
end={Number(item)}
duration={8}
/>
);
}
})}
</div>
</div>
</>
);
};
export default CountTo;
3.style.less
@font-face {
font-family: "Digital-7";
src: url("../../../assets/fonts/digital-7-4.ttf");
font-weight: normal;
font-style: normal;
}
.countToBox {
position: relative;
display: flex;
justify-content: center;
padding-bottom: 16px;
.countToMain {
padding: 0 100px;
.countToSplit {
display: inline-block;
width: 20px;
height: 60px;
line-height: 60px;
font-size: 42px;
font-family: 'Digital-7';
margin: 0 4px;
color: #fff;
background: rgba(0, 0, 0, 0.01);
border-image: linear-gradient(to bottom, #8bc0f1, #5e4dea) 2 10;
text-align: center;
}
.countToSumNum {
display: inline-block;
width: 40px;
height: 60px;
line-height: 60px;
font-size: 42px;
font-family: 'Digital-7';
margin: 0 4px;
color: #fff;
background: rgba(0, 0, 0, 0.01);
border: 2px transparent solid;
border-image: linear-gradient(to bottom, #8bc0f1, #5e4dea) 2 10;
text-align: center;
font-weight: 700;
}
}