【发布时间】:2020-12-05 18:40:56
【问题描述】:
我正在使用 FlatList - React Native 实现一个 Slider,
我有两个案例
- 按下可转到下一张幻灯片
- 按下可跳过并转到 Slider 中的最后一项
所以首先我应该知道我所在的当前索引并基于它 我滚动到下一项,
为了获得这个索引,我应该使用onMomentumScrollEnd,但问题是,它不会在 Android 中触发
onMomentumScrollEnd={(ev) => {
offsetRef.current = ev.nativeEvent.contentOffset.x;
console.log('ev', ev.nativeEvent.contentOffset.x);
console.log(' offsetRef.current', offsetRef.current);
}}
const NextButton = () => {
return (
<TouchableOpacity
onPress={() =>
flatListRef.current.scrollToOffset({
animated: true,
offset: offset.current + width,
})
}>
<Text style={{color: '#fff', fontSize: 16}}>Next</Text>
</TouchableOpacity>
);
};
const _renderSkipButton = () => {
return (
<AnimatedButton
onPress={() => {
// animation();
// setDoneBtn((prev) => !prev);
flatListRef.current.scrollToIndex({
animated: true,
index: data.length - 1, // Not work!
});
}}
style={[styles.buttonCircle, {transform: [{translateY: skipButton}]}]}>
<Text>skip</Text>
</AnimatedButton>
);
};
<Animated.FlatList
data={data.reverse()}
keyExtractor={(item) => item.title}
horizontal
ref={flatListRef}
showsHorizontalScrollIndicator={false}
pagingEnabled
scrollEventThrottle={16}
contentContainerStyle={{
paddingBottom: 100,
flexDirection: 'row-reverse',
}}
onScroll={Animated.event(
[{nativeEvent: {contentOffset: {x: scrollX}}}],
{useNativeDriver: false},
)}
onMomentumScrollEnd={(ev) => {
const index = Math.round(ev.nativeEvent.contentOffset.x / ITEM_WIDTH);
const newIndex = I18nManager.isRTL ? data.length - index - 1 : index;
indexItem.current = newIndex;
console.log('onMomentumScrollEnd', newIndex);
}}
renderItem={....}
/>
【问题讨论】:
-
为什么要使用偏移量来表示上一个/下一个,而使用索引来表示跳过?
-
@J.Doe for skip 我去最后一个索引它的工作将(我将索引 0)因为我的应用程序是 RTL,对于下一个 prev,我只是尝试索引和偏移但是没有按预期工作!
标签: android react-native react-native-android react-native-flatlist