</> resetField:
(name: string, options?: Record<string, boolean | any>) => void
重置单个字段状态。
¥Reset an individual field state.
属性
¥Props
调用该函数后。
¥After invoke this function.
-
isValid
表单状态将被重新评估。¥
isValid
form state will be reevaluated. -
isDirty
表单状态将被重新评估。¥
isDirty
form state will be reevaluated.
ResetField
具有保留场状态的能力。以下是你可能想要使用的选项:
¥ResetField
has the ability to retain field state. Here are the options you may want to use:
名称 | 类型 | 描述 | |
---|---|---|---|
name | string | 注册的字段名称。 | |
options | keepError | boolean | 当设置为 true 时,字段错误将被保留。 |
keepDirty | boolean | 当设置为 true 时,dirtyFields 将被保留。 | |
keepTouched | boolean | 当设置为 true 时,touchedFields 状态将保持不变。 | |
defaultValue | unknown | 当未提供此值时,字段将恢复为默认值。 当提供此值时:
|
RULES
-
名称需要与注册的字段名称匹配。
¥name need to match registered field name.
register("test")resetField("test") // ✅ register input and resetField worksresetField("non-existent-name") // ❌ failed by input not found
示例:
¥Examples:
重置字段状态
¥Reset Field State
import * as React from "react"import { useForm } from "react-hook-form"export default function App() {const {register,resetField,formState: { isDirty, isValid },} = useForm({mode: "onChange",defaultValues: {firstName: "",},})const handleClick = () => resetField("firstName")return (<form><input {...register("firstName", { required: true })} /><p>{isDirty && "dirty"}</p><p>{isValid && "valid"}</p><button type="button" onClick={handleClick}>Reset</button></form>)}
使用选项重置
¥Reset With Options
import * as React from "react"import { useForm } from "react-hook-form"export default function App() {const {register,resetField,formState: { isDirty, isValid, errors, touchedFields, dirtyFields },} = useForm({mode: "onChange",defaultValues: {firstName: "",},})return (<form><input {...register("firstName", { required: true })} /><p>isDirty: {isDirty && "dirty"}</p><p>touchedFields: {touchedFields.firstName && "touched field"}</p><p>dirtyFields:{dirtyFields.firstName && "dirty field"}</p><p>isValid: {isValid && "valid"}</p><p>error: {errors.firstName && "error"}</p><hr /><buttontype="button"onClick={() => resetField("firstName", { keepError: true })}>Reset keep error</button><buttontype="button"onClick={() => resetField("firstName", { keepTouched: true })}>Reset keep touched fields</button><buttontype="button"onClick={() => resetField("firstName", { keepDirty: true })}>Reset keep dirty fields</button><buttontype="button"onClick={() => resetField("firstName", { defaultValue: "New" })}>update defaultValue</button></form>)}
视频
¥Video
以下视频教程演示了 resetField
API。
¥The following video tutorial demonstrates resetField
API.