-->

React native flatlist initial scroll to bottom

2020-08-17 05:32发布

问题:

I am trying to create a chat in React native using a <Flatlist />

Like WhatsApp and other chat apps, the messages start at the bottom.

After fetching the messages from my API, I call

this.myFlatList.scrollToEnd({animated: false});

But it scrolls somewhere in the middle and sometimes with fewer items to the bottom and sometimes it does nothing.

How can I scroll initially to the bottom?

My chat messages have different heights, so I can't calculate the height.

回答1:

I had similar issue. If you want to have you chat messages start at the bottom, you could set "inverted" to true and display your messages and time tag in an opposite direction.

Check here for "inverted" property for FlatList. https://facebook.github.io/react-native/docs/flatlist#inverted

If you want to have you chat messages start at the top, which is what I am trying to achieve. I could not find a solution in FlatList, because as you said, the heights are different, I could not use getItemLayout which make "scrollToEnd" behave in a strange way.

I follow the approach that @My Mai mentioned, using ScrollView instead and do scrollToEnd({animated: false}) in a setTimeout function. Besides, I added a state to hide the content until scrollToEnd is done, so user would not be seeing any scrolling.



回答2:

I faced the same issue with you and then I moved to use ScrollView. It is fixed:

componentDidMount() {
  setTimeout(() => {
    this.scrollView.scrollToEnd();
  });
}

<ScrollView ref={(ref) => { this.scrollView = ref; }} style={styles.messages}>
      {
        messages.map((item, i) => (
          <Message 
            key={i} 
            direction={item.userType === 'banker' ? 'right' : 'left'} 
            text={item.message} 
            name={item.name}
            time={item.createdAt}
          />
        ))
      }
    </ScrollView>`


回答3:

Set initialScrollIndex to your data set's length - 1.

I.e.

<Flatlist
data={dataSet}
initialScrollIndex={dataSet.length - 1}
/>


回答4:

I am guessing that RN cannot guess your layout so it cannot know how much it needs to "move". According to the scroll methods in the docs you might need to implement a getItemLayout function, so RN can tell how much it needs to scroll.

https://facebook.github.io/react-native/docs/flatlist.html#scrolltoend



回答5:

Guys if you want FlatList scroll to bottom at initial render. Just added inverted={-1} to your FlatList. I have struggle with scroll to bottom for couple of hours but it ends up with inverted={-1}. Don't need to think to much about measure the height of FlatList items dynamically using getItemLayout and initialScrollIndex or whats so ever.