forked from relax/react-counter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
88 lines (73 loc) · 1.88 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
var React = require('react');
var raf = require('raf');
var ease = require('ease-component');
var createClass = require('create-react-class');
var Counter = createClass({
getInitialState: function() {
return {
value: this.props.begin,
time: this.props.time,
begin: this.props.begin,
end: this.props.end,
easing: this.props.easing,
start: Date.now(),
stop: false,
isMounted: false
};
},
componentDidMount: function() {
this.isMounted = true;
raf(this.animate);
},
componentWillUnmount: function() {
this.isMounted = false;
},
animate: function() {
if (this.state.stop) return;
raf(this.animate);
this.draw();
},
componentWillReceiveProps: function(nextProps) {
this.setState({
time: nextProps.time,
begin: nextProps.begin,
end: nextProps.end,
easing: nextProps.easing,
start: Date.now(),
stop: false
}, function() {
raf(this.animate);
this.draw();
});
},
draw: function() {
if (!this.isMounted) return;
var time = this.state.time;
var begin = this.state.begin;
var end = this.state.end;
var easing = this.state.easing;
easing = easing && easing in ease ? easing : 'outCube';
var now = Date.now();
if (now - this.state.start >= time) {
this.setState({
stop: true
});
}
var percentage = (now - this.state.start) / time;
percentage = percentage > 1 ? 1 : percentage;
var easeVal = ease[easing](percentage);
var val = begin + (end - begin) * easeVal;
this.setState({
value: val
});
},
render: function() {
var value = this.props.formatFunc ? this.props.formatFunc(this.state.value) : Math.round(this.state.value);
return React.createElement(
'span',
{ className: 'counter' },
value
);
}
});
module.exports.Counter = Counter;