如何转到平面列表中的特定项目(索引) [英] How to go to a specific item(index) in FlatList
本文介绍了如何转到平面列表中的特定项目(索引)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我看到this,但我做不到。 我有一个名为Days的静态列表,并将其绑定到FlatList,如下所示:
const DAYS = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
]
const App = () => {
const onViewRef = useRef((viewableItems) => {
})
const viewConfigRef = useRef({ viewAreaCoveragePercentThreshold: 50 })
return (
<View style={styles.screen}>
<Button title="Go To" onPress={() => { }} />
<FlatList
data={DAYS}
horizontal={true}
showsHorizontalScrollIndicator={false}
keyExtractor={(item, index) => index.toString()}
onViewableItemsChanged={onViewRef.current}
viewabilityConfig={viewConfigRef.current}
renderItem={({ item }) =>
<View style={styles.textContainer}>
<Text style={styles.text}>{item}</Text>
</View>}
/>
</View>
)
}
运行后:
现在,当我点击按钮(转到)时,FlatList应该如下所示:
(例如,转到项目10,所选项目应居中)
推荐答案
通过阅读scrollToIndex和getItemLayout,您可能可以:
const DAYS = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30
]
const ITEM_WIDTH = 20 // size of you element
const App = () => {
const flatListRef = useRef(null)
const onViewRef = useRef((viewableItems) => {
})
const viewConfigRef = useRef({ viewAreaCoveragePercentThreshold: 50 })
return (
<View style={styles.screen}>
<Button title="Go To" onPress={() => {
if (flatListRef.current) {
flatListRef.current.scrollToIndex({index: 9}) // Scroll to day 10
}
}} />
<FlatList
ref={flatListRef} // add ref
getItemLayout={(data, index) => (
{length: ITEM_WIDTH, offset: ITEM_WIDTH * index, index}
)}
data={DAYS}
horizontal={true}
showsHorizontalScrollIndicator={false}
keyExtractor={(item, index) => index.toString()}
onViewableItemsChanged={onViewRef.current}
viewabilityConfig={viewConfigRef.current}
renderItem={({ item }) =>
<View style={styles.textContainer}>
<Text style={styles.text}>{item}</Text>
</View>}
/>
</View>
)
}
这篇关于如何转到平面列表中的特定项目(索引)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文