Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to Animate React Native Text Value

so basically im trying to get this render function to actually update the value in real time (as of now it just jumps to the final value upon completion of the animation)

this.state = {
  pleaseDisplayMe: Animated.value(0);
}

triggerAnimation(){
  Animated.timing(
        this.state.pleaseDisplayMe,
        {toValue: 100,
        duration: 5000}
      ).start();
}

render(){
  return  <Animated.Text>{this.state.pleaseDisplayMe}</Animated.Text>
}

I feel like because this library can animated values under the hood then there must be a way to display whats happening. Or is there some sort of content/value property I can feed in through style?

I've tried custom writing my own setInterval function, but I need it to line up better with other Animations' timing and I'd love access to RN's Easing library!

thanks!

like image 363
Jeremy Avatar asked Feb 10 '17 01:02

Jeremy


People also ask

How do I get Animated value React Native?

To get the current value of Animated. Value with React Native, we call addListener on the animated value object. to call spinValue. addListener with a callback to get the current value of the animated value from the value property.

How do you reset Animated value React Native?

You can use this. spinValue. setValue(0) to reset it. You can add it at the beginning of handlePress .

What is Animated value?

Standard value for driving animations. One Animated. Value can drive multiple properties in a synchronized fashion, but can only be driven by one mechanism at a time. Using a new mechanism (e.g. starting a new animation, or calling setValue ) will stop any previous ones.


1 Answers

React Native has timers that you can use. For example, to do what you are trying to accomplish with setInterval:

state = {pleaseDisplayMe: 0}

componentDidMount() {
  setInterval(() => {
    this.setState({pleaseDisplayMe: this.state.pleaseDisplayMe + 1})
  }, 1000);
}

render() {
  return (
    <Text>{this.state.pleaseDisplayMe}</Text>
  )
}

However, if you are trying to instead trying to actually get the value from the animation, you should attach a listener to Animated and get the value from there as there is no way to synchronously read the value because it might be driven natively. A possibly very poor (I'm also new to React Native) example of this would be something like this:

state = {
  pleaseDisplayMe: new Animated.Value(0),
  value: 0,
}

triggerAnimation(){
  this.state.pleaseDisplayMe.addListener(({value}) => this.setState({value: value}));
  Animated.timing(
    this.state.pleaseDisplayMe,
    {toValue: 100,
    duration: 5000}
  ).start();
}

render() {
  return (
    <Text>{this.state.value}</Text>
  )
}
like image 100
Michael Cheng Avatar answered Oct 24 '22 12:10

Michael Cheng