我正在构建一个简单的水平 React Native FlatList 并启用分页:
<FlatList
horizontal={true}
pagingEnabled={true}
data={...some data...}
renderItem={({item}) => {...some rendering...}}
onViewableItemsChanged={(info) => {... handling ...}}
/>
我希望只有在列表中的新页面可见后才被召回。我正在寻求的行为是,当用户向左和向右滑动列表时,列表将翻阅项目,我希望回调对可见项目触发一次。
onViewableItemsChanged
除非我跟踪这些项目属于哪个页面,否则在可见项目的每一个变化上都会调用 props,这不是我正在寻找的。我在找
onViewablePageChanged
回调类型。关于如何实现这一目标的任何想法?
最佳答案
我使用的解决方案是根据整个项目列表跟踪可查看项目,以确定可查看项目的“页面”数量。
通过使用 pagingEnabled
,列表将只显示页面。
然而onViewableItemsChanged
对可查看项目的每次更改都会回调。通过将可查看的项目与项目列表进行比较,可以确定 FlatList 位于哪个“页面”。
这要求人们知道 View 中可以显示多少项。要么基于布局计算,要么在 View 和 FlatList 渲染中设置。
下面是一个例子:
onViewableItemsChanged = ({viewableItems}) => {
// Get the first viewable item
const firstViewableItem = viewableItems[0].key;
// Get its index into the items
const index = this.state.items.findIndex(item => item.key === firstViewableItem);
// If the index is a multiple of the number of items displayable on the screen
// by checking for a reminder on the modulo operation
if ((index % NB_ITEMS_SCREEN) === 0) {
// get page
const currentPage = index / NB_ITEMS_SCREEN;
if (currentPage !== this.state.currentPage) {
// Do something and update currentPage in this.state
}
}
}
<FlatList
data={this.state.items}
horizontal={true}
pagingEnabled={true}
renderItem={({ item }) => <Text>{item.key}</Text>}
onViewableItemsChanged={this.onViewableItemsChanged}
/>
看到这个小吃
https://snack.expo.io/@visto9259/flatlist-onviewableitemschanged-example
关于react-native - 使用分页 FlatList,如何更改可见页面上的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55405977/