首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在ScrollView react-native中自动滚动

在ScrollView react-native中自动滚动
EN

Stack Overflow用户
提问于 2018-06-15 12:53:25
回答 2查看 11.9K关注 0票数 4

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

下面是我的代码:

代码语言:javascript
运行
复制
<ScrollView>
  <FlatList
    data={this.state.dataSource}
    renderItem={({ item }) => <SenderChatRow data={item} />}
    keyExtractor={(item, index) => index}
  />
  {this._bookingRequestMessage()}
</ScrollView>
EN

回答 2

Stack Overflow用户

发布于 2018-06-15 13:01:05

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

代码语言:javascript
运行
复制
<ScrollView
    ref={ref => this.scrollView = ref}
    onContentSizeChange={(contentWidth, contentHeight)=>{        
        this.scrollView.scrollToEnd({animated: true});
    }}>
</ScrollView>

看看Docs

更新

正如你提到的,当键盘打开时,你会遇到问题,首先:

import { Keyboard } from "react-native";

然后使用componentDidMount()

代码语言:javascript
运行
复制
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的更新!

票数 11
EN

Stack Overflow用户

发布于 2018-06-15 13:19:15

对于scrollview,将下面这几行添加到scrollview中

代码语言:javascript
运行
复制
<ScrollView
            ref={(ref) => this.flatListRef = ref}
            contentContainerStyle={{ flex: 1 }}
            onContentSizeChange={(width, height) => this.flatListRef.scrollToEnd({ animated: false })}
          >

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

代码语言:javascript
运行
复制
componentDidMount() {
    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));
}
}

 componentWillUnmount() {
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
  }
  
  _keyboardDidShow() {
    this.scrollView.scrollToEnd({ animated: false })
  }

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50869299

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档