礼记有言:独学而无友,则孤陋而寡闻
让我们一起了解更多便捷方法,缩短开发时间去摸鱼,嘿嘿。
框架:react
在写表单的时候,我不太喜欢把验证写的很繁琐,这里讲介绍,验证表单的非常好用的验证库:Formik + Zod 和 Formik + Yup 。
其实,react-hook-form +Zod 的 周下载量也超级高,不过我还是更喜欢Formik,这里react-hook-form 就不做介绍了,留给by搜索引擎需要form表单的公主or 王子 一个选择,礼记有言:教学相长。如果你有更好的方法,也可以分享给我哟,嘿嘿。
formik 的使用
radio
import React from 'react';
import { useFormik } from 'formik';export function FormikStudyRadio() {const formik = useFormik({initialValues: {gender: '',},onSubmit: (values) => {alert(JSON.stringify(values, null, 2));},validate: (values) => {console.log(values.gender, '-')if (!values.gender) {return { gender: "请选择你的性别" };}console.log(values.gender);},});return (<form onSubmit={formik.handleSubmit} className='flex items-center gap-2'><label>男<inputtype="radio"name="gender"value="male"checked={formik.values.gender === 'male'}onChange={formik.handleChange}/></label><div><label>女<inputtype="radio"name="gender"value="female"checked={formik.values.gender === 'female'}onChange={formik.handleChange}/></label></div>{formik.touched.gender && formik.errors.gender ? (<div className='text-red-400'>{formik.errors.gender}</div>) : null}<button type="submit" className="p-2 border border-gray-400 ml-4 rounded-[8px]">Submit</button></form>);
}
checkbox
import React from "react";
import { useFormik } from "formik";export const FormikStudy = () => {const formik = useFormik({initialValues: {friends: [],},onSubmit: (values) => {alert(JSON.stringify(values, null, 2));},validate: (values) => {if (!values.friends.length) {return { friends: "Required!" };}console.log(values.friends);},});return (<div ><form onSubmit={formik.handleSubmit} className="[&>label]:text-xl [&>label]:mr-4 [&>label>input]:mr-1 text-left"><label><inputname="friends"type="checkbox"onChange={formik.handleChange}value="carrot"/>carrot</label><label><inputname="friends"type="checkbox"onChange={formik.handleChange}value="monet"/>monet</label><button className="p-2 border border-gray-400 ml-4 rounded-[8px]" type="submit">Submit</button></form><div className="text-red-600 text-sm text-left">{formik.errors.friends}</div></div>);
};
普通文本
Formik + Zod
import React from "react";
import { useFormik } from "formik";
import { z } from "zod";
import { withZodSchema } from "formik-validator-zod";const validationSchema = z.object({name: z.string().min(8, { message: "Must be 8 or more characters long" }),desc: z.string().nonempty(),email: z.string().email({ message: "Invalid email address" }),
})const valuesType = ["text", "text", 'email']type ValuesState = {name: string,desc: string,email: string
}
const initialValues: ValuesState = {name: '',desc: '',email: ''
}
export const FormikStudy2 = () => {const formik = useFormik({initialValues,validate: withZodSchema(validationSchema),onSubmit: (values) => {alert(JSON.stringify(values, null, 2));},});const errors: any = formik.errors.valueOf()return (<div><form onSubmit={formik.handleSubmit} className="flex flex-col gap-2 m-2">{Object.keys(initialValues).map((key, index) => <div key={index} className="flex flex-col items-start"><div><label htmlFor={`${key}`}>{key}:</label><inputclassName="border border-gray-400 p-1 ml-1 rounded-lg"id={`${key}`}// name={`${key}`}type={`${valuesType[index]}`}// onChange={formik.handleChange}// value={formik.values[`${key}`]}{...formik.getFieldProps(`${key}`)}/></div><div className="text-red-600 text-sm text-left">{formik.errors && formik.errors.hasOwnProperty(key) && errors[`${key}`]}</div></div>)}<button type="submit" className="w-[100px] p-2 border border-gray-400 rounded-[8px]">Submit</button></form></div>);
};