简体   繁体   中英

React Native FlatList: how to reset scroll position

I have a horizontal FlatList in my React Native iOS app. At the bottom of the screen, the FlatList is displayed with 5 items. If you click on the last item (scrolled all the way to the right), the screen will refresh and the FlatList will remain scrolled to the right. How can I get the FlatList to always reset the scroll position (to scroll from the beginning) when the screen changes?

Edit: I have a feeling that my screen is not actually "refreshing" but rather merely changing the data shown on the screen. In this case I may need to trigger a refresh of the screen somehow to cause the FlatList to reset the scroll position? Any help would be greatly appreciated!

const HorizontalScroll = ({items, handlePress}) => {  

  const renderItem = ({item}) => {
    const itemData = { color: item.color, title: item.title };
    return <HorizontalItem itemData={itemData} handlePress={handlePress}  />;
  };
    
  return (
    <View style={styles.container}>
      <FlatList
        data={items}
        renderItem={renderItem}
        horizontal={true}
        numColumns={1}
        key={(item) => item.id}
        initialNumToRender={5}
        scrollToIndex={0}
        ItemSeparatorComponent={() => <View style={{width: 8}} />}>
      </FlatList>
    </View>
  );
 };

I solved this problem by forcing a refresh of the component. Specifically, I added a key prop to my component so that every time the key value changes, it remounts the component. This causes the FlatList to reset the scroll position to the beginning.

<View key={items[0].title}>
    {content}
</View>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM