https://react-hook-form.com/
完全基于 Hooks 实现的表单状态管理框架
- 通过非受控组件的方式进行表单元素的管理
- 可以避免很多的表单重新渲染,从而对于复杂的表单组件可以避免性能问题
- React Hook Form 也没有绑定到任何 UI 库,需要自己处理布局和错误信息的展示
npm install react-hook-form
use
import React from "react";
import { useForm } from "react-hook-form";
export default function App() {
const { register, handleSubmit, watch, formState: { errors } } = useForm();
const onSubmit = data => console.log(data);
console.log(watch("example")); // watch input value by passing the name of it
return (
/* "handleSubmit" will validate your inputs before invoking "onSubmit" */
<form onSubmit={handleSubmit(onSubmit)}>
{/* register your input into the hook by invoking the "register" function */}
<input defaultValue="test" {...register("example")} />
{/* include validation with required or other standard HTML validation rules */}
<input {...register("exampleRequired", { required: true })} />
{/* errors will return when field validation fails */}
{errors.exampleRequired && <span>This field is required</span>}
<input type="submit" />
</form>
);
}
Formik
Formik 只提供了表单状态逻辑的重用,并没有限制使用何种 UI 库
- 你要自己管理如何进行 UI 布局以及错误信息的展示
- Formik 将所有的表单状态都,通过 render props 的回调函数传递给了表单的 UI 展现层