自动滚动在ScrollView react-native

Yas*_*ela 2 javascript react-native

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

这是我的代码:

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

Moh*_*h75 7

在React Native 0.41和更高版本中,您可以使用以下命令:

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

看看Docs

更新资料

如前所述,打开键盘时遇到问题,首先:

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 })
}
Run Code Online (Sandbox Code Playgroud)

感谢chetan godiya的更新!