react-native - 使用分页 FlatList,如何更改可见页面上的事件?

标签 react-native react-native-flatlist

我正在构建一个简单的水平 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/

相关文章:

react-native - 当水平为真时,百分比不适用于 FlatList 渲染项

react-native - FlatList 单选单元格

reactjs - 如果 React Native 中的 React Navigation 库提供的堆栈导航器组件不存在 initialRouteName Prop 会发生什么

android - 如何使用 AsyncStorage React Native 缓存 API 数据

reactjs - {React Native} Async\Await 无法与 setState 正常工作

reactjs - 组合点击以关闭键盘、键盘避免 View 和提交按钮

reactjs - 每次选择/取消选择一行时,如何避免 react 原生 FlatList 重新渲染

Firebase onAuthStateChanged unsubscribe is not a function 错误

react-native - 添加新项目时防止倒置的 Flatlist 滚动到底部

javascript - this.state.users 是一个数组,但仍然不会在 FlatList 中呈现