问题描述
我看到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>
)
}