</> getFieldState:
(name: string, formState?: Object) => ({isDirty, isTouched, invalid, error})
该方法以 react-hook-form (v7.25.0) 表单引入,用于返回各个字段状态。如果你尝试以类型安全的方式检索嵌套字段状态,它会很有用。
¥This method is introduced in react-hook-form (v7.25.0) to return individual field state. It's useful in case you are trying to retrieve nested field state in a typesafe way.
属性
¥Props
名称 | 类型 | 描述 |
---|---|---|
name | string | 注册的字段名称。 |
formState | object | 这是一个可选属性,仅当 formState 未从 useForm 、useFormContext 或 useFormState 读取/订阅时才需要。阅读规则以获取更多信息 |
返回
¥Return
名称 | 类型 | 描述 |
---|---|---|
isDirty | boolean | 字段被修改为 条件:订阅 dirtyFields 。 |
isTouched | boolean | 字段已收到焦点和模糊事件。 条件:订阅 touchedFields 。 |
invalid | boolean | 字段无效。 条件:订阅 errors 。 |
error | undefined | FieldError | 字段错误对象. 条件:订阅 errors 。 |
-
名称需要与注册的字段名称匹配。
¥name needs to match a registered field name.
getFieldState("test")getFieldState("test") // ✅ register input and return field stategetFieldState("non-existent-name") // ❌ will return state as false and error as undefined -
getFieldState
通过订阅 form 状态更新来工作,可以通过以下方式订阅 formState:¥
getFieldState
works by subscribing to the form state update, and you can subscribe to the formState in the following ways:-
你可以在
useForm
、useFormContext
或useFormState
订阅。这将建立表单状态订阅,并且不再需要getFieldState
第二个参数。¥You can subscribe at the
useForm
,useFormContext
oruseFormState
. This is will establish the form state subscription andgetFieldState
second argument will no longer be required.const {register,formState: { isDirty },} = useForm()register("test")getFieldState("test") // ✅const { isDirty } = useFormState()register("test")getFieldState("test") // ✅const {register,formState: { isDirty },} = useFormContext()register("test")getFieldState("test") // ✅ -
当未设置表单状态订阅时,你可以按照以下示例将整个
formState
作为第二个可选参数传递:¥When form state subscription is not setup, you can pass the entire
formState
as the second optional argument by following the example below:const { register } = useForm()register("test")const { isDirty } = getFieldState("test") // ❌ formState isDirty is not subscribed at useFormconst { register, formState } = useForm()const { isDirty } = getFieldState("test", formState) // ✅ formState.isDirty subscribedconst { formState } = useFormContext()const { touchedFields } = getFieldState("test", formState) // ✅ formState.touchedFields subscribed
-
示例
¥Examples
import * as React from "react"import { useForm } from "react-hook-form"export default function App() {const {register,getFieldState,formState: { isDirty, isValid },} = useForm({mode: "onChange",defaultValues: {firstName: "",},})// you can invoke before render or within the render functionconst fieldState = getFieldState("firstName")return (<form><input {...register("firstName", { required: true })} />{" "}<p>{getFieldState("firstName").isDirty && "dirty"}</p>{" "}<p>{getFieldState("firstName").isTouched && "touched"}</p><buttontype="button"onClick={() => console.log(getFieldState("firstName"))}>field state</button></form>)}