-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCounter.js
43 lines (33 loc) · 978 Bytes
/
Counter.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
import React, { Component } from 'react';
import { Text } from 'react-native';
export default class Counter extends Component{
constructor(props){
super(props);
this.state = { value: this.props.start };
// First Start
this.start();
}
componentWillReceiveProps(){
// Change Start
this.start();
}
start(){
this.startTime = Date.now();
requestAnimationFrame(this.loop.bind(this));
}
loop(){
const { time, start, end } = this.props;
const now = Date.now();
if ( now - this.startTime <= time ) requestAnimationFrame(this.loop.bind(this));
const percentage = Math.min((now - this.startTime) / time, 1); // 0 - 1
const value = start + ((end - start) * percentage);
this.setState({ value });
}
render(){
const { digits, style } = this.props;
const { value } = this.state;
let suffix = this.props.suffix;
suffix = suffix == undefined ? '' : ' ' + suffix;
return( <Text style={style}>{value.toFixed(digits) + suffix}</Text> );
}
}