如何使用文本输入 React Native 创建自定义对话框?
React Native 是 Facebook 开发的一个框架,用于在一种通用语言 JavaScript 下为 iOS 和 Android 创建原生风格的应用程序。在本文中,我们将创建一个带有文本输入的对话框。为了实现这一点,我们将使用 React Native 的内置 Modal 组件,我们将其用作 Dialog。
有两种方法可以创建 React Native 应用程序,您可以使用其中任何一种方法,但我们将使用 expo-CLI 来创建我们的应用程序。在这里,您可以找到创建 RN 应用程序的两种方法。创建 RN 应用程序有一些先决条件。您应该已经安装了以下工具。
- 节点 12 LTS 或更高版本
- 世博会-CLI
要安装 expo-CLI:运行以下命令。
npm install -g expo-cli
or
yarn global add expo-cli
创建App: TestApp是应用的名字,你可以随意使用其他名字
expo init TestApp
运行应用程序:进入应用程序文件夹运行命令。
cd TestApp
expo start
App.js:运行所有这些命令后,您应该有一个名为 TestApp 的目录,其中将包含您的 React Native 应用程序的文件。我们将编辑我们的App.js文件以创建一个对话框。
Javascript
import { StatusBar } from "expo-status-bar";
import React, { useState } from "react";
import { Button, SafeAreaView, StyleSheet, Modal,
View, TextInput, Dimensions } from "react-native";
const { width } = Dimensions.get("window");
export default function App() {
// This is to manage Modal State
const [isModalVisible, setModalVisible] = useState(false);
// This is to manage TextInput State
const [inputValue, setInputValue] = useState("");
// Create toggleModalVisibility function that will
// Open and close modal upon button clicks.
const toggleModalVisibility = () => {
setModalVisible(!isModalVisible);
};
return (
{/** We are going to create a Modal with Text Input. */}
{/** This is our modal component containing textinput and a button */}
setInputValue(value)} />
{/** This button is responsible to close the modal */}
);
}
// These are user defined styles
const styles = StyleSheet.create({
screen: {
flex: 1,
alignItems: "center",
justifyContent: "center",
backgroundColor: "#fff",
},
viewWrapper: {
flex: 1,
alignItems: "center",
justifyContent: "center",
backgroundColor: "rgba(0, 0, 0, 0.2)",
},
modalView: {
alignItems: "center",
justifyContent: "center",
position: "absolute",
top: "50%",
left: "50%",
elevation: 5,
transform: [{ translateX: -(width * 0.4) },
{ translateY: -90 }],
height: 180,
width: width * 0.8,
backgroundColor: "#fff",
borderRadius: 7,
},
textInput: {
width: "80%",
borderRadius: 5,
paddingVertical: 8,
paddingHorizontal: 16,
borderColor: "rgba(0, 0, 0, 0.2)",
borderWidth: 1,
marginBottom: 8,
},
});
输出: