</> useFormState:
({ control: Control }) => FormState
此自定义钩子允许你订阅每个表单状态,并在自定义钩子级别隔离重新渲染。它在表单状态订阅方面有其范围,因此不会影响其他 useFormState 和 useForm。使用此钩子可以减少对大型复杂表单应用的重新渲染影响。
¥This custom hook allows you to subscribe to each form state, and isolate the re-render at the custom hook level. It has its scope in terms of form state subscription, so it would not affect other useFormState and useForm. Using this hook can reduce the re-render impact on large and complex form application.
属性
¥Props
名称 | 类型 | 描述 |
---|---|---|
control | Object | control 对象由 useForm 提供。如果你使用 FormProvider ,则它是可选的。 |
name | string | string[] | 提供单个输入名称、输入名称数组或订阅所有输入的 formState 更新。 |
disabled | boolean = false | 禁用订阅的选项。 |
exact | boolean = false | 此属性将为输入名称订阅启用精确匹配。 |
返回
¥Return
名称 | 类型 | 描述 |
---|---|---|
isDirty | boolean | 在用户修改任何输入后设置为 true 。
|
dirtyFields | object | 具有用户修改字段的对象。确保通过 useForm 提供所有输入的 defaultValues ,以便库可以与 defaultValues.
|
touchedFields | object | 包含用户交互过的所有输入的对象。 |
defaultValues | object | 已在 useForm 的 defaultValues 或通过 reset API 更新的 defaultValues 中设置的值。 |
isSubmitted | boolean | 提交表单后设置为 true 。将保持 true ,直到调用 reset 方法。 |
isSubmitSuccessful | boolean | 表明表单已成功提交,没有任何运行时错误。 |
isSubmitting | boolean | true (如果当前正在提交表单)。否则为 false 。 |
isLoading | boolean | 如果表单当前正在加载异步默认值,则为 true 。
|
submitCount | number | 表单提交的次数。 |
isValid | boolean | 如果表单没有任何错误,则设置为 true 。
|
isValidating | boolean | 验证期间设置为 true 。 |
validatingFields | boolean | 捕获正在进行异步验证的字段。 |
errors | object | 存在字段错误的对象。还有一个 ErrorMessage 组件可以轻松检索错误消息。 |
disabled | boolean | 如果通过 useForm 中的 disabled 属性禁用表单,则设置为 true。 |
RULES
返回的 formState
用 Proxy 封装,以提高渲染性能,如果未订阅特定状态,则跳过额外计算,因此请确保在渲染之前解构或读取它以启用订阅。
¥Returned formState
is wrapped with Proxy to improve render performance and skip extra computation if specific state is not subscribed, so make sure you deconstruct or read it before render in order to enable the subscription.
const { isDirty } = useFormState() // ✅const formState = useFormState() // ❌ should deconstruct the formState
示例
¥Examples
import { useForm, useFormState } from "react-hook-form"function Child({ control }) {const { dirtyFields } = useFormState({ control })return dirtyFields.firstName ? <p>Field is dirty.</p> : null}export default function App() {const { register, handleSubmit, control } = useForm({defaultValues: {firstName: "firstName",},})const onSubmit = (data) => console.log(data)return (<form onSubmit={handleSubmit(onSubmit)}><input {...register("firstName")} placeholder="First Name" /><Child control={control} /><input type="submit" /></form>)}