我正在创建聊天应用,并希望每次收到新消息时自动在ScrollView
内自动滚动到底部。
这是我的代码:
<ScrollView>
<FlatList
data={this.state.dataSource}
renderItem={({ item }) => <SenderChatRow data={item} />}
keyExtractor={(item, index) => index}
/>
{this._bookingRequestMessage()}
</ScrollView>
答案 0 :(得分:4)
从React Native 0.41及更高版本开始,您可以使用:
import { Keyboard } from "react-native";
查看Docs
正如您所提到的,当键盘打开时您遇到问题,首先:
componentDidMount()
然后使用componentDidMount() {
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow',
this._keyboardDidShow.bind(this));
}
componentWillUnmount() {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
}
_keyboardDidShow() {
this.scrollView.scrollToEnd({ animated: false })
}
:
{{1}}
感谢chetan godiya更新!
答案 1 :(得分:0)
用于scrollview 将此行添加到您的滚动视图
<ScrollView
ref={(ref) => this.flatListRef = ref}
contentContainerStyle={{ flex: 1 }}
onContentSizeChange={(width, height) => this.flatListRef.scrollToEnd({ animated: false })}
>
然后从react-native add导入Keyboard,然后将此代码添加到脚本中
componentDidMount() {
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));
}
}
componentWillUnmount() {
this.keyboardDidShowListener.remove();
this.keyboardDidHideListener.remove();
}
_keyboardDidShow() {
this.scrollView.scrollToEnd({ animated: false })
}