如何在每次点击时按 15 项显示 Flatlist 的索引和结尾

How to show the index and end of the Flatlist by 15 items on every click

我需要在单击向上和向下按钮时显示列表的索引和底部。

如果我单击向上或向下箭头,是否有仅显示向上或向下 15 个项目的选项。

例如)考虑一个列表有 500 个项目。它有一个向上和向下的箭头。如果我单击向下箭头一次,我第一次只需要显示 15 个项目,如果单击向下箭头,则需要显示接下来的 15 个项目。

此外,如果我点击向上箭头,它需要显示上面的 15 个项目,而不是全部

在这个用例中,我需要在屏幕上上下移动。修改 Flatlist 中的 scrollToIndex 和 scrollToEnd 以实现此用例的任何选项

   upButtonHandler = () => {
        //OnCLick of Up button we scrolled the list to top
        this.ListView_Ref.scrollToOffset({ offset: 0,  animated: true });
      };

   downButtonHandler = () => {
    //OnCLick of down button we scrolled the list to bottom
     this.ListView_Ref.scrollToEnd({ animated: true });
    };

 <TouchableOpacity
    activeOpacity={0.5}
      onPress={this.downButtonHandler}
      style={styles.downButton}>
      <Image
        source={{uri:'https://raw.githubusercontent.com/AboutReact/sampleresource/master/arrow_down.png',
        }}
        style={styles.downButtonImage}
      />
    </TouchableOpacity>
    <TouchableOpacity
      activeOpacity={0.5}
      onPress={this.upButtonHandler}
      style={styles.upButton}>
      <Image
        source={{uri:'https://raw.githubusercontent.com/AboutReact/sampleresource/master/arrow_up.png',
        }}
        style={styles.upButtonImage}
      />
    </TouchableOpacity>

您可以 slice 每次按钮 FlatList 时提供给 FlatList 的数据 pressed.As FlatList 是一个纯组件,您需要将 extra 道具传递给按下按钮后重新渲染 FlatList

维护一个状态变量,例如描述要显示数据的哪一部分的部分,例如 (0,15),(15,30),...

在向上和向下按钮中更新这个变量,注意边界以免变坏 results.This 很容易通过将 setState 包装在 if 条件中来解决,这样看起来会很粗略作为

updateSectionLow = () => {
    const { section } = this.state;
    if (section > 0) {
      this.setState({
        section: section - 1,
      });
    }
  };
  updateSectionHigh = () => {
    const { section, data } = this.state;
    if (data.length > (section + 1) * 15) {
      this.setState({
        section: section + 1,
      });
    }
  };

FlatList 看起来像这样

<FlatList
   data={this.state.data.slice(this.state.section*15,(this.state.section+1)*15)}
   renderItem={({ item }) => {
            return (
              <View style={styles.row}>
                <Text>{item.data}</Text>
              </View>
            );
   }}
   extraData={this.state.section}
/>

这是工作展demo

编辑 与OP人员讨论后,我稍微更改了我的代码。

获取滚动后的偏移量, 对于垂直列表

onMomentumScrollEnd={e => this.scroll(e.nativeEvent.contentOffset)}

处理程序内部

this.setState({
  index: Math.floor(offset.y / (ITEM_HEIGHT+SEPARATOR_HEIGHT)),
});

如果没有分隔符那么你可以将SEPARATOR_HEIGHT设为0

只需要按如下方式使用带有 ref 的 scrollToOffset

在列表中下降 ITEMS_DISP(如 15)

this.flatListRef.scrollToOffset({
    offset:(this.state.index+ITEMS_DISP)*ITEM_HEIGHT+(this.state.index+ITEMS_DISP)*SEPARATOR_HEIGHT
  });

由于某些 ITEMS_DISP

位居榜首
this.flatListRef.scrollToOffset({
    offset:(this.state.index-ITEMS_DISP)*ITEM_HEIGHT+(this.state.index-ITEMS_DISP)*SEPARATOR_HEIGHT
  });

已更新演示 link