簡體   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