我在 KeyboardAvoidingView 中有一个 FlatList。显示键盘时,我想滚动到 FlatList 的末尾。
我正在监听确实被触发的“keyboardDidShow”事件,但它可能被触发得太早,因为在调用 scrollToEnd 后 FlatList 没有滚动到末尾。
我已经查看了 KeyboardAvoidingView 的 onLayout 事件,但是仅将 onLayout 事件设置为触发函数似乎会阻止 KeyboardAvoidingView 在显示键盘时调整其大小。
<KeyboardAvoidingView behavior='padding' style={{ flex: 1}} onLayout={this._scrollEnd}>
代码:
import React from 'react';
import {Image, Linking, Platform, ScrollView, StyleSheet, Text, TouchableOpacity, View, Button, Alert, FlatList, TextInput, KeyboardAvoidingView, Keyboard} from 'react-native';
import { MonoText } from '../components/StyledText';
export default class HomeScreen extends React.Component {
constructor() {
super();
this.state = {
messages: getMessages()
};
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._scrollEnd);
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidHide', this._scrollEnd);
}
_scrollEnd = (evt) => {
this.refs.flatList1.scrollToEnd();
}
render() {
return (
<KeyboardAvoidingView behavior='padding' style={{ flex: 1}} >
<FlatList
style={{ flex:1}}
ref="flatList1"
data={this.state.messages}
renderItem={({ item }) => <Text>{item.text}</Text>}
/>
</KeyboardAvoidingView>
);
}
}
原文由 Andrew Arthur 发布,翻译遵循 CC BY-SA 4.0 许可协议
实际上,如果您总是想滚动到最后,意味着您总是想看到最新消息,对吗?
然后使用新版本的 react-native。并添加 倒置 以改变平面列表的倒置。
然后重新排列你的 this.state.messages 颠倒。那么您的最新消息将始终显示在平面列表的底部
就我而言,我不需要使用 KeyboardAvoidingView