在官方的react-native文档中,有一节关于Animated.event方法.例如,他们使用以下代码:
onScroll={Animated.event( // scrollX = e.nativeEvent.contentOffset.x [{ nativeEvent: { contentOffset: { x: scrollX } } }] )}
我想将正确的值映射到Animated.event方法,我还想将onScroll回调参数映射到我自己的回调.基本上我想做这样的事情:
onScroll={(event) => { myOwnCallback(event.nativeEvent.contentOffset.x) Animated.event( // scrollX = e.nativeEvent.contentOffset.x [{nativeEvent: { contentOffset: { x: scrollX } } }] ) }}
你能解释一下如何做到这一点吗?
解决方法
当你查看源代码时:
/** * 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,
这就是我的工作方式:
onScroll={Animated.event( [{ nativeEvent: { contentOffset: { y: this.state.scrollY } } }],{ useNativeDriver: true,listener: event => { const offsetY = event.nativeEvent.contentOffset.y // do something special },},)}