PHP前端开发

简化表单验证:React Hook 表单与传统方法

百变鹏仔 2个月前 (10-14) #JavaScript
文章标签 表单

表单验证是 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 (    
{errors.firstname &&

{errors.firstname}

} {errors.lastname &&

{errors.lastname}

} {errors.email &&

{errors.email}

} {errors.password &&

{errors.password}

} {/* more form fields */} {issubmitting ? "submitting..." : "submit"} );};

采用这种传统方法

虽然这可行,但它涉及大量样板代码,对于较大的表单可能会变得很麻烦。

输入react hook form

安装

npm install react-hook-form
import React from "react";// useForm is the hook which is given by react-hook-formimport { 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 (    
{errors.firstName &&

{errors.firstName.message}

} {errors.lasttName &&

{errors.lasttName.message}

} {errors.email &&

{errors.email.message}

} {errors.firstName &&

{errors.firstName.message}

} {/* More form fields */} {isSubmitting ? "Submitting..." : "Submit"} );};

react hook form 的简单性

了解如何在具有更多输入字段的打字稿中处理react-hook-form

感谢您的阅读...希望您今天学到了新东西:)