簡體   English   中英

將數據添加到 FlatList 的開頭而不更改 position

[英]Add data to begining of FlatList without changing position

我正在嘗試在 flatlist 中實現類似道具的“onBeginReached”。 我想 append 以對用戶透明的方式在我的數據數組開頭的一些數據。

所以使用這個 flatList:

const App = () => {
  const flatListRef = useRef(null);
  const [data, setData] = useState(generateData(20));

  const renderItem = ({ item }) => {
  console.log(item);
  return (
    <View style={styles.itemContainer}>
      <Text style={styles.itemText}>{item}</Text>
    </View>
  );
};

  const handleMomentumScroll = (event) => {
    console.log("Momentum end")
    const xOffset = event.nativeEvent.contentOffset.x;
    const index = Math.round(xOffset / 30);

    if (index < 1) {
      setData([-10 ,-9, -8, -7, -6,-5, -3, -2, -1, ...data]);
    }
  };

  return (
    <FlatList
      style={{ width: 200, alignSelf: 'center', marginTop: 150 }}
      initialScrollIndex={10}
      horizontal
      data={data}
      snapToAlignment={'start'}
      decelerationRate={'fast'}
      snapToInterval={30}
      getItemLayout={(data, index) => ({
         length: 30,
         offset: 30 * index,
         index,
      })}
      keyExtractor={(item, index) => index.toString()}
      renderItem={renderItem}
      onMomentumScrollEnd={handleMomentumScroll}
    />
  );
};

const styles = StyleSheet.create({
  itemContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    width: 30,
    height: 30,
    borderRadius: 15,
    backgroundColor: 'blue',
  },
  itemText: {
    color: 'white',
  },
});

( https://snack.expo.io/GUblotbZc )

如果我滾動到索引 0,它會將我的新數據移到我的數據數組中。 但是,它會自動滾動到新數據數組的第一個索引。 在將新數據移到數組時,我想保留當前的 position。

有一種方法可以實現這種行為嗎?

這是演示: https://snack.expo.io/@nomi9995/flatlisttest

在 IOS 中使用maintainVisibleContentPosition VisibleContentPosition 道具來防止自動滾動,但不幸的是,它不適用於 android 但好消息是 android 的拉取請求已經到來,需要與本機反應合並。

<FlatList
  ref={(ref) => { this.chatFlatList = ref; }}
  style={styles.flatList}
  data={this.state.items}
  renderItem={this._renderItem}
  maintainVisibleContentPosition={{
     minIndexForVisible: 0,
  }}
/>

我這樣做的方法是使用inverted屬性反轉 FlatList,同時反轉我的列表。 這樣,FlatList 的頂部將位於底部,我的數組中的最后一項在那里可見。 當用戶滾動到頂部onEndReached被觸發,我將新項目添加到數組的開頭,它們將被添加到 FlatList 的頂部而不更改頂部的當前可見項目。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM