ScrollToEnd after update data for Flatlist

我的未来我决定 提交于 2019-11-29 15:25:59
Ourabi

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()} /> 
Tuan Nguyen Quoc

Thanks @Kernael, just add a timeout like so:

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

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.

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