ReactNative [Flatlist] scrollToOffset,如何计算点击行的偏移位置?
ReactNative [Flatlist] scrollToOffset, how do I figure out offset position of clicked row?
我希望 FlatList 中的一行在用户单击时滚动到屏幕顶部。我目前正在使用 scrollToIndex
方法来执行此操作,但问题是我必须为顶部边距设置动画(从 10 到 0)以使其刷新到屏幕顶部。我还有一个问题,如果用户单击一行以展开该行,并且前一行已经展开,则前一行将折叠,导致原始 scrollToIndex 动画到屏幕顶部的某个位置。
我目前的两个选择是在前一行完成收缩后触发额外的 scrollToIndex
或使用 scrollToOffset
根据良好的旧数学值确定滚动到的位置。有没有办法在单击时按索引或其他值计算行偏移位置?
感谢任何人可能提供的帮助!
我没有尝试使用 scrollToOffset
方法找出滚动到的位置,而是仍在使用 scrollToIndex
方法并使用 viewOffset
参数来计算如何滚动要添加到该方法的偏移量:任何其他当前展开的项目(如果有)的展开高度和折叠高度之间的差值减去被单击项目的上边距。
您可以使用 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
})
我希望 FlatList 中的一行在用户单击时滚动到屏幕顶部。我目前正在使用 scrollToIndex
方法来执行此操作,但问题是我必须为顶部边距设置动画(从 10 到 0)以使其刷新到屏幕顶部。我还有一个问题,如果用户单击一行以展开该行,并且前一行已经展开,则前一行将折叠,导致原始 scrollToIndex 动画到屏幕顶部的某个位置。
我目前的两个选择是在前一行完成收缩后触发额外的 scrollToIndex
或使用 scrollToOffset
根据良好的旧数学值确定滚动到的位置。有没有办法在单击时按索引或其他值计算行偏移位置?
感谢任何人可能提供的帮助!
我没有尝试使用 scrollToOffset
方法找出滚动到的位置,而是仍在使用 scrollToIndex
方法并使用 viewOffset
参数来计算如何滚动要添加到该方法的偏移量:任何其他当前展开的项目(如果有)的展开高度和折叠高度之间的差值减去被单击项目的上边距。
您可以使用 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
})