0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

React Native CounterのsetStateする側

Last updated at Posted at 2018-05-25

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
    })
  }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?