您可以使用 scrollToItem 来实现您想要实现的目标
所以假设你有这个 FlatList 组件
<FlatList
ref={(ref) => { this._flatList = ref; }}
data = {dataSourche}
renderItem = {( info: {item:item, index:number}) => this._renderFlatListItem(info.item, info.index)}
keyExtractor = {(item) => item.id}
decelerationRate={0}
snapToInterval={cardHeight}
snapToAlignment={"start"} //Can also be 'center' or 'end'
onMomentumScrollEnd = {(event) => this._onMomentumScrollEnd(event)}
getItemLayout = {this.getItemLayout}/>
您需要定义一个方法 getItemLayout 来告诉 flatList 3 件事
- 长度:在您的情况下卡片的高度
- 偏移量:这是从列表顶部到当前卡片的距离,通常我们可以将其设置为长度 * 卡片索引
- 卡片索引
所以这是一个示例 getItemLayout,您可以参考
getItemLayout = (data, index) => (
{ length: 170, offset: 170 * index, index }
);
接下来将是您的 FlatList scrollToItem 调用
this._flatList.scrollToItem({
animated:true, //can also be false
item:item,
viewPosition:0 //this is the first position that is currently attached to the window
})