Skip to content

resetField

重置字段状态和值

</> 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:

名称类型描述
namestring注册的字段名称。
optionskeepErrorboolean当设置为 true 时,字段错误将被保留。
keepDirtyboolean当设置为 true 时,dirtyFields 将被保留。
keepTouchedboolean当设置为 true 时,touchedFields 状态将保持不变。
defaultValueunknown当未提供此值时,字段将恢复为默认值。
当提供此值时:
  • field will be updated with the supplied value
  • field's defaultValue will be updated to this value.
  • Only support non undefined value.
RULES
  • 名称需要与注册的字段名称匹配。

    ¥name need to match registered field name.

    register("test")
    resetField("test") // ✅ register input and resetField works
    resetField("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 />
<button
type="button"
onClick={() => resetField("firstName", { keepError: true })}
>
Reset keep error
</button>
<button
type="button"
onClick={() => resetField("firstName", { keepTouched: true })}
>
Reset keep touched fields
</button>
<button
type="button"
onClick={() => resetField("firstName", { keepDirty: true })}
>
Reset keep dirty fields
</button>
<button
type="button"
onClick={() => resetField("firstName", { defaultValue: "New" })}
>
update defaultValue
</button>
</form>
)
}

视频

¥Video


以下视频教程演示了 resetField API。

¥The following video tutorial demonstrates resetField API.

React Hook Form 中文网 - 粤ICP备13048890号