[英]How to create flatlist auto scroll with Hooks in React Native
I'm trying to create an auto scroll flatlist carousel that can also allow the user to scroll manually.我正在尝试创建一个自动滚动平面列表轮播,它还可以允许用户手动滚动。 The problem is that I get this error
flatListRef.scrollToIndex is not a function
.问题是我收到此错误
flatListRef.scrollToIndex is not a function
。 I tried searching how other people create an auto scroll flatlist but their solution is using class.我尝试搜索其他人如何创建自动滚动平面列表,但他们的解决方案是使用 class。
const flatListRef = useRef(null)
useEffect (() => {
const totalIndex = data.length - 1;
setInterval (() => {
if(flatListRef.current.index < totalIndex) {
flatListRef.scrollToIndex({animated: true, index: flatListRef.current.index + 1})
} else {
flatListRef.scrollToIndex({animated: true, index: 0})
}
}, 3000)
}, []);
const renderItem = ({item}) => {
return (
<View style={styles.cardView}>
<Image style={styles.image} source={item.image} resizeMode="contain"/>
</View>
)
}
return (
<View style={{paddingHorizontal: 10}} >
<FlatList
ref={flatListRef}
data={data}
keyExtractor={data => data.id}
horizontal
pagingEnabled
scrollEnabled
snapToAlignment="center"
scrollEventThrottle={16}
decelerationRate={"fast"}
showsHorizontalScrollIndicator={true}
persistentScrollbar={true}
renderItem={renderItem}
/>
</View>
);
styles: styles:
cardView: {
flex: 1,
width: width - 20,
height: height * 0.21,
backgroundColor: Colors.empty,
alignItems: 'center',
justifyContent: 'center',
},
image: {
backgroundColor: Colors.empty,
width: width - 20,
height: height * 0.21,
},
useRef returns a mutable object whose.current property is initialized to initial value. useRef 返回一个可变的 object ,其.current 属性被初始化为初始值。 So basically you need to access scrollIndex like this
所以基本上你需要像这样访问scrollIndex
flatListRef.current.scrollToIndex({animated: true, index: flatListRef.current.index + 1})
as per the guide on React Native onScrollToIndexFailed根据React Native onScrollToIndexFailed的指南
you have to override你必须覆盖
onScroll={(e) => {
this.setState({ currentIndex: Math.floor(e.nativeEvent.contentOffset.x / (dimensions.wp(this.props.widthPercent || 100) - 1)) });
}}
onScrollToIndexFailed={info => {
const wait = new Promise(resolve => setTimeout(resolve, 500));
wait.then(() => {
this.carouselRef?.scrollToIndex({ index: 0, animated: true });
});
}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.