刷新页面 或者定时刷新数据的时候 比如我想显示的数字是100000, 正常刷新的时候 , 数据会直接从0到1000000 , 我想从0 渐变递增到1000000, 该如何实现呢, 其实使用js也可以实现的, 在此项目中 我使用了d3
import React from 'react';
import PropTypes from 'prop-types';
import injectSheet from 'react-jss';
import { inject } from 'mobx-react';
import Counter from '../../../../../commonComps/counter/index.js';
import './index.styl';
import { get } from 'client/util/http'; // eslint-disable-line
import { fail } from 'client/util/utils'; // eslint-disable-line
const styles = () => ({
publishRoot: {
width: '100%',
height: '100%',
'& .iconfont': {
color: '#00b4ed',
},
},
});
@injectSheet(styles)
@inject('CatalogManageStore')
class AllTimes extends React.Component {
static propTypes = {
classes: PropTypes.object,
}
constructor() {
super();
this.state = {
publishValue: 0,
};
}
getNumber = (n) => {
if (n >= 1e+12) {
return <React.Fragment><Counter data={Number((n / 1e+12).toFixed(4))} />万亿</React.Fragment>;
} else if (n >= 1e+8) {
return <React.Fragment><Counter data={Number((n / 1e+8).toFixed(4))} />亿</React.Fragment>;
} else if (n >= 1e+4) {
return <React.Fragment><Counter data={Number((n / 1e+4).toFixed(4))} />万</React.Fragment>;
}
return <Counter data={n} />;
}
render() {
const { classes } = this.props;
const { publishValue, createValue, data } = this.state;
return (
<div className={classes.publishRoot} id="allTimes">
<div className="item">
<div className="name">已发布服务</div>
<div className="num">{this.getNumber(publishValue)}</div>
<span className="bgIcon"><i className="icon iconfont icon-yifabudefuwu" /></span>
</div>
</div>
);
}
}
export default AllTimes;
counter.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { fromJS } from 'immutable';
import PlayCounter from './render';
export default class Counter extends Component {
constructor(props) {
super(props);
this.num = 0;
}
componentDidMount() {
PlayCounter(this.counter, this.props.data, this.num);
}
shouldComponentUpdate(nextProps) {
if (!fromJS(nextProps).equals(fromJS(this.props))) {
return true;
}
return false;
}
componentDidUpdate() {
PlayCounter(this.counter, this.props.data, this.num);
this.num = this.props.data;
}
render() {
return (
<span className="counter" ref={(node) => { this.counter = node; }} />
);
}
}
Counter.propTypes = {
data: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
]),
};
render.js
import * as d3 from 'd3';
export default function PlayCounter(id, data, num) {
const duration = 1000;
d3.select(id)
.text(num)
.transition()
.duration(duration)
.tween('text', () => {
const i = d3.interpolate(num, data);
function count(t) {
let content = 0;
if (t === 1) {
content = data;
} else {
content = Math.round(i(t));
}
d3.select(id)
.text(content);
// this.textContent = content;
}
return count;
});
}