React Nativeで数字のアップダウンのアニメーションをしたい
↓
npmでreact-native-counterを発見
↓
初回だけしかアニメーションしてくれない(+PropTypes非推奨のエラー)
↓
任意のタイミング(ボタンクリックなど)で何度もアニメーションするようなものがほしい
↓
見つからない...
そのようなパッケージありましたら教えてください
とりあえずreact-native-counterで必要なものだけバラしてそれっぽいのを作りました
counter.js
import eases from 'eases'
const counter = ({
start,
end,
setState,
time = 1000,
digits = 0,
easing = 'linear',
onComplete = null
}) => {
this.start = start
this.end = end
this.setState = setState
this.time = time
this.digits = digits
this.easing = easing
this.onComplete = onComplete
this.startTime = Date.now()
this.stop = false
requestAnimationFrame(animate.bind(this))
}
const animate = () => {
if (this.stop) {
if (this.onComplete) this.onComplete()
return
}
requestAnimationFrame(animate.bind(this))
draw()
}
const draw = () => {
const now = Date.now()
if (now - this.startTime >= this.time) this.stop = true
const percentage = Math.min((now - this.startTime) / this.time, 1)
const easeVal = eases[this.easing](percentage)
const value = this.start + (this.end - this.start) * easeVal
this.setState(value.toFixed(this.digits))
}
export default counter
Usage
import React from 'react'
import counter from './counter'
class Hoge extends React.Component {
state = { value: 0 }
onClick = () => {
const setState = value => this.setState({ value })
counter({
start: this.state.value,
end: 100,
setState
})
}
}