Song Yongtao
Song Yongtao

Reputation: 835

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?

Upvotes: 10

Views: 1766

Answers (1)

remeus
remeus

Reputation: 2424

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

Upvotes: 7

Related Questions