表单验证是 Web 开发的一个重要方面,可确保数据完整性并增强用户体验。在 React 生态系统中,我们看到了处理表单及其验证方式的重大演变。
React 中的传统表单验证
import React, { useState } from "react"; const SimpleForm = () => { const [formData, setFormData] = useState({ firstName: "", lastName: "", email: "", password: "", // ... other fields }); const [errors, setErrors] = useState({}); const [isSubmitting, setIsSubmitting] = useState(false); const handleChange = (e) => { const { name, value } = e.target; setFormData({ ...formData, [name]: value, }); }; const handleSubmit = (e) => { e.preventDefault(); setIsSubmitting(true); const newErrors = {}; // Validation logic if (!formData.firstName) newErrors.firstName = "First Name is Required"; if (!formData.lastName) newErrors.lastName = "Last Name is Required"; if (!formData.email.match(/^\S+@\S+$/i)) newErrors.email = "Invalid email address"; if (!formData.password.match(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/)) newErrors.password = "Invalid password"; // ... more validation rules if (Object.keys(newErrors).length > 0) { setErrors(newErrors); return; } // Submit form data try { const response = await simulateApiCall(formData); console.log("Success: ", response); } catch (error) { console.error(error); setError({ root: error.message }); } finally { setIsSubmitting(false) } }; return ( <form onSubmit={handleSubmit}> <input name="firstName" value={formData.firstName} onChange={handleChange} /> {errors.firstName && <p>{errors.firstName}</p>} <input name="lastName" value={formData.lastName} onChange={handleChange} /> {errors.lastName && <p>{errors.lastName}</p>} <input name="email" value={formData.email} onChange={handleChange} /> {errors.email && <p>{errors.email}</p>} <input type="password" name="password" value={formData.password} onChange={handleChange} /> {errors.password && <p>{errors.password}</p>} {/* More form fields */} <button type="submit" disabled={isSubmitting}> {isSubmitting ? "Submitting..." : "Submit"} </button> </form> ); };
采用这种传统方法
虽然这有效,但它涉及大量样板代码,对于较大的表单可能会变得很麻烦。
输入 React Hook 表单
安装
npm install react-hook-form
import React from "react"; // useForm is the hook which is given by react-hook-form import { useForm } from "react-hook-form"; const ReactHookForm = () => { const { register, handleSubmit, setError, formState: { errors, isSubmitting }, } = useForm(); const onSubmit = (data) => { // Submit form data try { const response = await simulateApiCall(formData); console.log("Success: ", response); } catch (error) { console.error(error); setError({ root: error.message }); } }; return ( <form onSubmit={handleSubmit(onSubmit)}> <input {...register("firstName", { required: "First Name is required" })} /> {errors.firstName && <p>{errors.firstName.message}</p>} <input {...register("lastName", { required: "Last Name is required" })} /> {errors.lasttName && <p>{errors.lasttName.message}</p>} <input {...register("email", { required: "Email is required", pattern: { value: /^\S+@\S+$/i, message: "Invalid email address" } })} /> {errors.email && <p>{errors.email.message}</p>} <input {...register("password", { required: "First Name is required", pattern: { value: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/, message: "Invalid password"} })} /> {errors.firstName && <p>{errors.firstName.message}</p>} {/* More form fields */} <button type="submit" disabled={isSubmitting}> {isSubmitting ? "Submitting..." : "Submit"} </button> </form> ); };
React Hook 表单的简单性
减少样板:React Hook Form 消除了手动状态管理的需要。表单数据和错误不再使用 useState。
声明式验证:我们不编写命令式验证逻辑,而是在寄存器函数中声明验证规则。这使得代码更具可读性和可维护性。
自动错误处理:React Hook Form 自动跟踪错误并通过错误对象提供错误,无需手动进行错误状态管理。
性能:通过利用不受控制的组件,React Hook Form 最大限度地减少了重新渲染,从而带来更好的性能,特别是对于大型表单。
轻松集成:注册功能与您现有的输入元素无缝集成,只需对 JSX 进行最少的更改。
内置验证:内置常见验证规则,如 required、min、max、pattern,减少了对自定义验证函数的需求。
TypeScript 支持:React Hook Form 提供出色的开箱即用的 TypeScript 支持,增强表单中的类型安全性。
了解如何在具有更多输入字段的打字稿中处理react-hook-form
虽然 React 中的传统表单处理为您提供了细粒度的控制,但它通常会导致难以维护的冗长代码。
React Hook Form 显着简化了这个过程,提供了一种更具声明性和更有效的方式来处理表单及其验证。
感谢您的阅读...希望您今天学到了新东西:)
以上是简化表单验证:React Hook 表单与传统方法的详细内容。更多信息请关注PHP中文网其他相关文章!