Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with React Native animated.timing in same child components

Parent Component:

routes.forEach((data, index) => {
  content.push(<Item key={index} offset={688} route={route} />)
})

Item Component:

scrollAnimate (toValue) {
  const { offset } = this.props;

  Animated.timing(
    this.state.xTranslate,
    {
      toValue,
      duration: 20000,
      easing: Easing.linear,
      useNativeDriver: true
    }
  ).start((e) => {
    if (e.finished) {
      const newState = {xTranslate: new Animated.Value(offset)}
      this.setState(newState, () => { this.scrollAnimate(toValue) })
    }
  });
}

I want every Item Component loop animate separate, but the fact is that all Item Components animation end and then all Item Component start the animation together. How can I fix it?

like image 822
Song Yongtao Avatar asked Jul 25 '19 11:07

Song Yongtao


People also ask

How do I stop animated timings in React Native?

If an animation is in process of being animated and, for any particular reason, you need to stop it, you can call stopAnimation . The stopAnimation call also takes a callback with the value that the animation was stopped on. this. _animatedValue = new Animated.

How do you check if animation is finished React Native?

The updated answer should be: . start(({finished}) => { if (finished) { console. log('animation ended!) } })

How do you loop animation in React Native?

In order to create looping animations in react native, we should use Animated. loop() method. Wrap your Animations within Animated. loop() and the animations will act as a loop.

How do you use interpolate in React Native?

In React Native, you can interpolate animated values using . interpolate which takes an inputRange, that interpolates and maps the values to an outputRange. Great thing is that you can interpolate numbers not just to other numbers but also to colours and degrees.


1 Answers

Well it looks like all your animations start at the same time and have the same duration so obviously they will end at the same time.

You can give them different duration or add different delays if you want to prevent them from being synchronized:

Animated.timing(
  this.state.xTranslate,
  {
    toValue,
    duration: 20000,
    easing: Easing.linear,
    useNativeDriver: true,
    delay: Math.random() * 1000, // Or pass it as this.props.delay
  }
)
like image 111
remeus Avatar answered Oct 31 '22 02:10

remeus