ScrollToEnd after update data for Flatlist

两盒软妹~` 提交于 2019-12-29 08:52:15

问题


I'm making a chat box with Flatlist. I want to add a new item to data then scroll to bottom of list. I use scrollToEnd method but it did not work. How can I do this?

<FlatList
        ref="flatList"
        data={this.state.data}
        extraData = {this.state}
        renderItem={({item}) => <Text style={styles.chatFlatListItem}>{item.chat}</Text>}
/>

AddChat(_chat){
    var arr = this.state.data;
    arr.push({key: arr.length, chat: _chat});
    var _data = {};
    _data["data"] = arr;
    this.setState(_data);
    this.refs.flatList.scrollToEnd();
 }

回答1:


I found a better solution,scrollToEnd() is not working because it is triggered before the change is made to the FlatList.
Since it inherits from ScrollView the best way here is to call scrollToEnd() in onContentSizeChange like so :

<FlatList
            ref = "flatList"
            onContentSizeChange={()=> this.refs.flatList.scrollToEnd()} /> 



回答2:


Thanks @Kernael, just add a timeout like so:

setTimeout(() => this.refs.flatList.scrollToEnd(), 200)



回答3:


Change your code as below. The ref is modified and It's better to use getItemLayout in your FlatList according to this.

AddChat(_chat){
    var arr = this.state.data;
    arr.push({key: arr.length, chat: _chat});
    var _data = {};
    _data["data"] = arr;
    this.setState(_data);
    this.flatList.scrollToEnd();
 }

<FlatList
    ref={elm => this.flatList = elm}
    data={this.state.data}
    extraData = {this.state}
    renderItem={({item}) => <Text style={styles.chatFlatListItem}>{item.chat}</Text>}
    getItemLayout={(data, index) => (
      {length: ITEM_HEIGHT, offset: ITEM_HEIGHT * index, index}
    )}
/>

Note: Replace the ITEM_HEIGHT with the real value of height of your list items.



来源:https://stackoverflow.com/questions/46304677/scrolltoend-after-update-data-for-flatlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!