用于构建表单和调查的 React 库
**由侯赛因·阿里夫✏️撰写**
虽然在 React 中构建表单很简单,但管理它们却很复杂。例如,如果不依赖表单库,开发人员必须:
为了缓解这些挑战,我们可以使用表单库来为我们处理大部分繁重的工作。在本文中,我们将介绍 React 生态系统中一些流行的表单库:
现在我们已经简单介绍了一些 React 表单库,让我们开始探索吧!
设置我们的 React 项目
在编写代码之前,我们必须先搭建 React 项目。为此,请在终端中运行以下命令:
#initialize React project with Typescript: npm create vite@latest form-libraries --template react-ts cd form-libraries npm install #install the needed packages to run the project.
React 表单库:SurveyJS
如前所述,SurveyJS 是一个用于构建多页表单和调查的库。它支持多种功能,包括:
要将 SurveyJS 包含在我们的项目中,请通过 npm 安装它:
npm install survey-react-ui --save
此代码块展示了 SurveyJS 库的实际作用:
import "survey-core/defaultV2.min.css";
import { Model, SurveyModel } from "survey-core";
import { Survey } from "survey-react-ui";
import { useCallback } from "react";
export function SurveyExample() {
//create our schema for our form:
const surveyJson = {
elements: [
//configure our fields
{
name: "FirstName",
title: "Enter your first name:",
type: "text",
},
{
name: "LastName",
title: "Enter your last name:",
type: "text",
},
],
};
//feed the schema into the model
const survey = new Model(surveyJson);
//handler function that runs when the user submits the form
const surveyComplete = useCallback((survey: SurveyModel) => {
const userOutput = survey.data;
console.log(userOutput);
}, []);
//attach this handler to the form
survey.onComplete.add(surveyComplete);
return (
{/*Finally, pass our model and render the form*/}
);
}
//don't forget to render this component in App.tsx!在上面的代码片段中:
让我们测试一下!要运行该项目,请输入以下命令:
npm run dev
React Hook 表单
React Hook Form 是一个无依赖的库,可以实现高效的表单验证。它具有以下特点:
与往常一样,第一步是在你的项目中安装 React Hook Form:
npm install react-hook-form
下面是一段演示 React Hook Form 中验证的代码:
import { useState } from "react";
import { useForm, SubmitHandler } from "react-hook-form";
type Inputs = {
twice: boolean;
newjeans: boolean;
name: string;
};
export default function ReactHookForm() {
const {
register,
handleSubmit,
watch,
formState: { errors },
} = useForm({ defaultValues: { twice: true, name: "LogRocket" } });
const [output, setOutput] = useState();
const onSubmit: SubmitHandler = (data) => setOutput(data);
return (
Your favorite group?
{output?.newjeans && "newjeans was selected"}
{output?.twice && "twice was selected"}
Name: {output?.name}
);
} 让我们逐一分解这段代码:
就这样!让我们测试一下 React Hook Form:
rc-字段形式
与 React Hook Form 类似,rc-field-form 是另一个注重性能和易用性的 React 表单库。
首先,只需安装依赖项,如下所示:
npm install rc-field-form
此代码片段展示了如何通过 rc-field-form 库在文本字段上实现异步验证:
import Form, { Field } from "rc-field-form";
const Input = ({ value = "", ...props }) => ;
export const RCFieldFormExample = () => {
return (
);
};以下是我们计划的简要说明:
以下是代码的输出:
太棒了!如你所见,我们的代码可以正常工作!
Tanstack 与 Zod 组建
Tanstack 团队无需介绍。最近,他们将 TanStack Form 引入了他们的高质量实用程序库。尽管仍处于测试阶段,但该库包含一系列详尽的功能,包括:
与往常一样,使用库的第一步是安装它:
#react-form: to render and build forms #zod-form-adapter and zod: For validation purposes. npm i @tanstack/react-form @tanstack/zod-form-adapter zod
接下来,让我们构建一个在发生验证错误时通知用户的组件:
import type { FieldApi } from "@tanstack/react-form";
function FieldInfo({ field }: { field: FieldApi }) {
return (
<>
{/*If error occurs, display it. */}
{field.state.meta.isTouched && field.state.meta.errors.length ? (
{field.state.meta.errors.join(",")}
) : null}
{field.state.meta.isValidating ? "Validating..." : null}
>
);
} 在这里,我们创建了一个名为“FieldInfo”的组件,它将检查用户是否未通过任何验证检查。如果满足此条件,它将在页面上显示错误。
最后,使用 Tanstack Form 编写以下代码块用于表单渲染和验证:
import { useForm } from "@tanstack/react-form";
import { zodValidator } from "@tanstack/zod-form-adapter";
import { z } from "zod";
//step 1: define our schema and each field's requirements
const userSchema = z.object({
//if the user's name is Log, display an error.
firstName: z.string().refine((val) => val !== "Log", {
message: "[Form] First name cannot be Log!",
}),
//the user's age should be atleast 18.
age: z.coerce.number().min(18, "Need to be an adult!"),
});
type User = z.infer;
export default function TanstackFormExample() {
//use the useForm hook and define our default values.
const form = useForm({
defaultValues: {
firstName: "",
age: 0,
} as User,
onSubmit: async ({ value }) => {
console.log(value);
},
//configure our validation
validatorAdapter: zodValidator(),
validators: {
onSubmit: userSchema,
},
});
return (
{
return state;
}}
children={(state) => {
return (
//check if the user can submit the form:
);
}}
/>
);
} 这段代码乍一看可能让人望而生畏,但其中大部分都是库运行所需的样板。解释在代码注释中。
运行时,TanStack Form 输出应如下所示:
比较我们介绍过的 React 表单库
下表比较了本指南中介绍的库:
在本文中,我们了解了 React 中的几个表单构建库。此外,我们还介绍了如何在这些库中对表单执行渲染和验证。在我的业余项目中,我使用 React Hook Form,因为它提供了可靠且高性能的解决方案以及用户友好的开发人员体验。这是本文的源代码。
当然,根据项目的需求,用户也可以选择 Formik 或 Ant Design 等库进行表单管理。
感谢您的阅读!
几分钟内即可设置 LogRocket 的现代 React 错误跟踪:
新版本:
$ npm i --save logrocket
// Code:
import LogRocket from 'logrocket';
LogRocket.init('app/id');脚本标记:
Add to your HTML:
立即开始