繁体   English   中英

在 ScrollView react-native 中自动滚动

[英]Auto scroll in ScrollView react-native

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

这是我的代码:

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

从 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的更新!

对于滚动视图,将此行添加到您的滚动视图中

 <ScrollView ref={(ref) => this.flatListRef = ref} contentContainerStyle={{ flex: 1 }} onContentSizeChange={(width, height) => this.flatListRef.scrollToEnd({ animated: false })} >

然后从 react-native add 导入键盘,然后将此代码添加到您的脚本中

 componentDidMount() { this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this)); } } componentWillUnmount() { this.keyboardDidShowListener.remove(); this.keyboardDidHideListener.remove(); } _keyboardDidShow() { this.scrollView.scrollToEnd({ animated: false }) }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM