在官方反应原生文档中,有一节关于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
}
}
}]
)
}}
请你解释一下如何做到这一点?
答案 0 :(得分:27)
当您查看源代码时:
/**
* 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
},
},
)}
答案 1 :(得分:0)
写处理程序函数
handleSctoll = (e) => {
console.log(e.nativeEvent.contentOffset.y);
}
,您可以像这样添加listener
Animated.event(
[{ nativeEvent: { contentOffset: { y: this.state.scrollY } } }],
{ listener: (event) => this.handleSctoll(event) }
)