React Native Virtual Keyboard使用KeyboardAwareScrollView阻止输入元素

7hiiyaii  于 2023-03-24  发布在  React
关注(0)|答案(1)|浏览(109)

我的iOS版React Native Expo应用程序有一个Home屏幕,显示一些聊天消息,并有一个文本输入元素,应该粘在设备屏幕的底部,就像大多数聊天应用程序一样。

Github repo:**一个

然而,当虚拟键盘向上滑动时,它隐藏了TextInput元素,尽管使用了KeyboardAwareScrollView

import { Text, TextInput, View } from "react-native";

import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view";
import { SafeAreaView } from "react-native-safe-area-context";
import { useState } from "react";

export default function Home() {
  const [input, setInput] = useState(null);
  const [numNewMessages, setNumNewMessages] = useState(0);

  // Simulate a new message received every few seconds
  setInterval(() => {
    setNumNewMessages((numNewMessages) => numNewMessages + 1);
  }, 3000);

  return (
    <SafeAreaView className="flex container h-full">
      <KeyboardAwareScrollView className="flex-grow bg-blue-100">
        {[...Array(10)].map((e, i) => (
          <Text key={i} className="my-10">
            Hello {i}!
          </Text>
        ))}

        {[...Array(numNewMessages)].map((e, i) => (
          <Text key={i} className="my-10">
            New msg {i}!
          </Text>
        ))}
      </KeyboardAwareScrollView>

      <View className="p-3">
        <TextInput
          className="placeholder:text-slate-400 block bg-white w-full border border-slate-300 rounded-md py-2 px-3 shadow-sm focus:outline-none focus:border-sky-500 focus:ring-sky-500 focus:ring-1 sm:text-sm"
          placeholder="Type your message"
          onChangeText={(value) => setInput(value)}
          value={input}
        />
      </View>
    </SafeAreaView>
  );
}

尝试将TextInput嵌套在KeyboardAwareScrollView中,但这会防止输入元素粘在底部屏幕上。
使用KeyboardAwareScrollViewSafeViewArea时如何解决此问题?谢谢!

o3imoua4

o3imoua41#

因此,在实现聊天系统时,我们需要在底部显示最新的消息,在此之前显示旧消息。因此,请记住这一点,假设我们有一个按newest to oldest排序的消息数组。

const messages = [
  {
    id: "1",
    message: "Hello World",
    created_at: "2023-03-22 10:15:00",
  },
  {
    id: "2",
    message: "Hello World 2",
    created_at: "2023-03-22 10:14:00",
  },
  .
  .
  .
  and so on
];

因此,我们希望的方法是以反转的形式显示它们。

<FlatList
  data={[...Array(20)]} // array of messages
  keyExtractor={(_, index) => index.toString()}
  renderItem={({ _, index }) => (
    <MessageItem
      key={index}
      message="Some Text Message"
    />
  )}
  inverted // This is important
/>

所以,重点是将FlatlistTextInput包裹在KeyboardAvoidingView内,这样当我们打开输入字段时,键盘平滑地滚动MainView和输入字段焦点。
为了理解实现,我创建了一个Snack,你可以看看我是如何实现它的。它按预期工作。

相关问题