限定时间内数字增长动画,先快后慢

 设定一个值跟时间,可选格式化数字(每三位加个逗号),可自定义className

 返回一个span标签

import React, {Component} from 'react';
import PropTypes from 'prop-types';

class ActiveNumber extends Component {
    state = {
        currentNumber: 0,
        showNumber: 0
    };

    constructor(props) {
        super(props);

    }

    componentDidMount() {
        let { delay=300, value=0, formatNumber=false } = this.props;
        // console.log(delay, value);
        let time = delay / value;
        let step, stepCount;
        // 最短每30ms为一帧
        if(time > 30) {
            step = value / delay;
            stepCount = delay / time;
        } else {
            time = 30;
            stepCount = delay / 30;
            step = value / stepCount;
        }
        console.log('time', time);
        console.log('expectStep', step);
        console.log('stepCount', stepCount);
        // return ;
        let startTime = new Date();
        let decrease = step / stepCount;
        // let change = step * 2;
        let change = step * 1.5;
        this.interval = setInterval(() => {
            // console.log(change);
            change = change > 1 ? change: 1;
            let currentNumber = this.state.currentNumber + change;
            currentNumber = currentNumber > value ? value: currentNumber;
            if(currentNumber >= value) {
                clearInterval(this.interval);
                let endTime = new Date();
                console.log('实际耗时:', endTime - startTime);
            }
           this.setState({ currentNumber });
           const showNumber = currentNumber.toString().split('.')[0];  
           if(formatNumber) this.setState({ showNumber: this.fomatNumber(showNumber)});
           else this.setState({ showNumber });
            change -= decrease;
        }, time)
    }

    /**
     * 数字每三位加逗号
     * @param numberOrString
     * @returns {string}
     */
    fomatNumber = numberOrString => {
        let str = String(numberOrString);
        let reg = str.indexOf(".") > -1 ? /(\d)(?=(\d{3})+\.)/g : /(\d)(?=(?:\d{3})+$)/g;
        return str.replace(reg,"$1,");
    }

    componentWillMount() {
        clearInterval(this.interval);
    }


    render() {
        let { className='' } = this.props;
        return (
            
                {this.state.showNumber}
            
        );
    }
}

export default ActiveNumber;

ActiveNumber.propTypes = {
  className: PropTypes.string,
  delay: PropTypes.number,
  formatNumber: PropTypes.bool,
  value: PropTypes.number.isRequired
};

ActiveNumber.defaultProps = {
  className: '',
  delay: 300,
  formatNumber: false,
  value: 0
};

demo:https://codepen.io/lister/pen/gJZLry?editors=1111

 

你可能感兴趣的:(限定时间内数字增长动画,先快后慢)