Search code examples
reactjsreact-nativescrollviewandroid-collapsingtoolbarlayoutreact-animated

React native animation scrollview onScroll event not working with external method


I make a collapsing tollbar in ReactNative and i need stop de animation when the Animated.ScrollView contentOffset.y is equal 240. If i put any condition or call the Animated.event in external function it dosn´t work.

The Animated.Value.stopAnimation() doesn´t work either.

This works:

<Animated.ScrollView
   scrollEventThrottle={1}
   onScroll={
     Animated.event(
       [{nativeEvent: {contentOffset: {y: this.state.scrollY}}}],
       {useNativeDriver: true}
     )
   }
>
...

This doesn´t work:

handlerScroll() {
  Animated.event(
    [{nativeEvent: {contentOffset: {y: this.state.scrollY}}}]
    {useNativeDriver: true}
  )
}
...
render() {
 return(
   <Animated.ScrollView
      scrollEventThrottle={1}
      onScroll={this.handlerScroll.bind(this)}
    >
 )
}
...

and this doesn´t work either

<Animated.ScrollView
   scrollEventThrottle={1}
   onScroll={
     this.state.canScroll &&
     Animated.event(
       [{nativeEvent: {contentOffset: {y: this.state.scrollY}}}],
       {useNativeDriver: true}
     )
   }
>
...

I don´t know what more i can use to stop my animation.

I need make this effect:

enter image description here


Solution

  • Instead of stopping scroll event mapping, why not use interpolate for your animation with extrapolate set to 'clamp'? This will stop your animation from going beyond the bounds of input and output values.

    Not sure what styles you’re trying to animate but for the sake of showing an example let’s say it was a translateY transform:

    // onScroll map data to Animated value
    onScroll={Animated.event(
        [{ nativeEvent: { contentOffset: { y: this.state.scrollY } } }],
        { useNativeDriver: true }
    )}
    
    <Animated.View
        style={{
            transform: [{
                translateY: this.state.scrollY.interpolate({
                    inputRange: [0, 240],
                    outputRange: [0, -160],
                    extrapolate: 'clamp' // clamp so translateY can’t go beyond -160
                })
            }]
        }}
    >
        ...
    </Animated.View>