首页 > 解决方案 > TextInput 在 React Native 中的键盘下消失

问题描述

我正在制作一个反应本机应用程序,由于某种原因,当我点击文本输入以键入一些内容时,它会在键盘下消失。我希望它像 Instagram Messenger 和其他 Messenger 应用程序那样位于键盘顶部。我尝试使用keyboardAvoidView 并将行为设置为填充和高度,但都没有奏效。

import {
  View,
  Text,
  StyleSheet,
  SafeAreaView,
  TextInput,
  TouchableOpacity,
} from "react-native";
import CommunityPost from "../components/CommunityPost";
import { Context as CommunityContext } from "../context/CommunityContext";

const Key = ({ navigation }) => {
  const { createCommunityPost, errorMessage } = useContext(CommunityContext);
  const [body, setBody] = useState("");


  return (
    <View style={styles.container}>
      <SafeAreaView />

      <CommunityPost />
      <View style={styles.inputContainer}>
        <TextInput
          style={styles.input}
          multiline={true}
          placeholder="Type..."
          placeholderTextColor="#CACACA"
          value={body}
          onChangeText={setBody}
        />
        <TouchableOpacity
          style={{ justifyContent: "center", flex: 1, flexDirection: "row" }}
          onPress={() => createCommunityPost({ body })}
        >
          <Text style={styles.sendText}>Send</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "flex-start",
    backgroundColor: "#2B3654",
    justifyContent: "flex-end",
  },
  inputContainer: {
    justifyContent: "flex-end",
    flexDirection: "row",
  },
  sendText: {
    color: "white",
    fontSize: 25,
  },
  input: {
    fontSize: 25,
    color: "white",
    borderColor: "#2882D8",
    borderWidth: 1,
    borderRadius: 15,
    width: "80%",
    marginBottom: 30,
    marginLeft: 10,
    padding: 10,
  },
});

export default Key;

键盘进程的 Gif

标签: javascriptreactjsreact-native

解决方案


您必须KeyboardAvoidingView由 react native 提供组件。

    <KeyboardAvoidingView
      behavior={Platform.OS == "ios" ? "padding" : "height"}
      style={styles.container}
    >
      <SafeAreaView />

      <CommunityPost />
      <View style={styles.inputContainer}>
        <TextInput
          style={styles.input}
          multiline={true}
          placeholder="Type..."
          placeholderTextColor="#CACACA"
          value={body}
          onChangeText={setBody}
        />
        <TouchableOpacity
          style={{ justifyContent: "center", flex: 1, flexDirection: "row" }}
          onPress={() => createCommunityPost({ body })}
        >
          <Text style={styles.sendText}>Send</Text>
        </TouchableOpacity>
      </View>
    </KeyboardAvoidingView>

推荐阅读