https://react-hook-form.com/
完全基于 Hooks 实现的表单状态管理框架

  • 通过非受控组件的方式进行表单元素的管理
  • 可以避免很多的表单重新渲染,从而对于复杂的表单组件可以避免性能问题
  • React Hook Form 也没有绑定到任何 UI 库,需要自己处理布局和错误信息的展示

image.png

  1. npm install react-hook-form

use

  1. import React from "react";
  2. import { useForm } from "react-hook-form";
  3. export default function App() {
  4. const { register, handleSubmit, watch, formState: { errors } } = useForm();
  5. const onSubmit = data => console.log(data);
  6. console.log(watch("example")); // watch input value by passing the name of it
  7. return (
  8. /* "handleSubmit" will validate your inputs before invoking "onSubmit" */
  9. <form onSubmit={handleSubmit(onSubmit)}>
  10. {/* register your input into the hook by invoking the "register" function */}
  11. <input defaultValue="test" {...register("example")} />
  12. {/* include validation with required or other standard HTML validation rules */}
  13. <input {...register("exampleRequired", { required: true })} />
  14. {/* errors will return when field validation fails */}
  15. {errors.exampleRequired && <span>This field is required</span>}
  16. <input type="submit" />
  17. </form>
  18. );
  19. }

Formik

Formik 只提供了表单状态逻辑的重用,并没有限制使用何种 UI 库

  • 你要自己管理如何进行 UI 布局以及错误信息的展示
  • Formik 将所有的表单状态都,通过 render props 的回调函数传递给了表单的 UI 展现层