React-native animated.event custom onScroll listener

后端 未结 2 1288
耶瑟儿~
耶瑟儿~ 2021-02-20 15:26

In official react-native documentation there is a section about Animated.event method. As example they use following code:

onScroll={Animated.event(         


        
相关标签:
2条回答
  • 2021-02-20 15:52

    Write handler function like:

        handleScroll = (e) => {
            console.log(e.nativeEvent.contentOffset.y);
        }
    

    and you can add listener like this:

        Animated.event(
           [{ nativeEvent: { contentOffset: { y: this.state.scrollY } } }],
           { listener: (event) => this.handleScroll(event) }
        )
    
    0 讨论(0)
  • 2021-02-20 15:59

    When you look at the source code:

    /**
       * Takes an array of mappings and extracts values from each arg accordingly,
       * then calls `setValue` on the mapped outputs.  e.g.
       *
       *```javascript
       *  onScroll={Animated.event(
       *    [{nativeEvent: {contentOffset: {x: this._scrollX}}}]
       *    {listener},          // Optional async listener
       *  )
       *  ...
       *  onPanResponderMove: Animated.event([
       *    null,                // raw event arg ignored
       *    {dx: this._panX},    // gestureState arg
       *  ]),
       *```
       *
       * Config is an object that may have the following options:
       *
       *   - `listener`: Optional async listener.
       *   - `useNativeDriver`: Uses the native driver when true. Default false.
       */
      event,
    

    This is how I made it work:

    onScroll={Animated.event(
                [{ nativeEvent: { contentOffset: { y: this.state.scrollY } } }],
      {
        useNativeDriver: true,
        listener: event => {
          const offsetY = event.nativeEvent.contentOffset.y
          // do something special
        },
      },
    )}
    
    0 讨论(0)
提交回复
热议问题