numColumns 中断 scrollToIndex 反应本机 FlatList

numColumns breaks scrollToIndex react native FlatList

我正在使用 React Native 的 FlatList 来显示项目列表,并检查当前可以查看哪些项目。在我的项目中,有一个标记为 mostUsed 的项目,如果该项目不可见,我会在顶部显示 link,用户可以单击它并使用 scrollToIndex 滚动到该项目。 scrollToIndex 在不设置 numColumns 的情况下运行良好,当我设置 numColumns={2} 时出现 scrollToIndex out of range: 9 vs 4 错误。

setScrollIndex = () => {
  if (this.state.scrollIndex !== 0) {
    return;
  }

  for (let i = 0; i < this.state.items.length; i++) {
    const items = this.state.items;

      if (items[i] && items[i].mostUsed) {
        this.setState({
          scrollIndex: i,
        });
      }
  }
};

// scroll to index function
scrollToIndex = () => {
  this.flatListRef.scrollToIndex({
    animated: true,
    index: this.state.scrollIndex,
  });
};

<FlatList
  data={this.state.items}
  numColumns={2}
  keyExtractor={(item, index) => index.toString()}
  ref={ref => {
    this.flatListRef = ref;
  }}
  showsVerticalScrollIndicator={false}
  onViewableItemsChanged={this.handleViewableItemsChanged}
  viewabilityConfig={this.viewabilityConfig}
  renderItem={({ item, index }) => (
    <Card  
      title={item.title}
      description={item.description}
      mostUsed={item.mostUsed}
      style={{ width: item.width }}
    />
  )}
/>

expo snack

如果 numColumns 高于 1,FlatListscrollToIndex 似乎改变了它查看索引的方式。

称它为 scrollToRowIndex 可能更正确,因为它不适用于多列的项目索引。

对于你的情况,这对我在世博会上有用:

scrollToIndex = () => {
  this.flatListRef.scrollToIndex({
    animated: true,
    index: Math.floor(this.state.scrollIndex / numColumns),
  });
};