react-countup 实现大屏数字自滚动效果

最终实现效果

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;
    }


  }

  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值