首页 > 解决方案 > ScrollView 中的自动滚动 react-native

问题描述

ScrollView我正在创建聊天应用程序,并希望在每次收到新消息时自动滚动到底部。

这是我的代码:

<ScrollView>
  <FlatList
    data={this.state.dataSource}
    renderItem={({ item }) => <SenderChatRow data={item} />}
    keyExtractor={(item, index) => index}
  />
  {this._bookingRequestMessage()}
</ScrollView>

标签: javascriptreact-native

解决方案


从 React Native 0.41 及更高版本你可以使用这个:

<ScrollView
    ref={ref => this.scrollView = ref}
    onContentSizeChange={(contentWidth, contentHeight)=>{        
        this.scrollView.scrollToEnd({animated: true});
    }}>
</ScrollView>

看看文档

更新

正如您提到的,您在打开键盘时遇到问题,首先:

import { Keyboard } from "react-native";

然后使用componentDidMount()

componentDidMount() {
  this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', 
    this._keyboardDidShow.bind(this));
}


componentWillUnmount() {
  this.keyboardDidShowListener.remove();
  this.keyboardDidHideListener.remove();
}

_keyboardDidShow() {
  this.scrollView.scrollToEnd({ animated: false })
}

感谢chetan godiya的更新!


推荐阅读