跳至内容

重置

重置表单状态和值

</> reset: <T>(values?: T | ResetAction<T>, options?: Record<string, boolean>) => void

重置整个表单状态、字段引用和订阅。存在可选参数,允许部分表单状态重置。

属性


Reset 能够保留 formState。以下是您可以使用的选项

名称类型描述
valuesobject一个可选对象,用于重置表单值,建议提供完整的 defaultValues(如果提供)。
keepErrorsboolean所有错误将保留。这不能保证在用户进一步操作后仍然如此。
keepDirtybooleanDirtyFields 表单状态将保留,isDirty 将暂时保留为当前状态,直到用户进行进一步操作。

重要:此 keep 选项不反映表单输入值,而只反映脏字段表单状态。
keepDirtyValuesbooleanDirtyFieldsisDirty 将保留,只有非脏字段将更新为最新的重置值。 查看示例。

重要:表单状态 dirtyFields 需要进行订阅。
keepValuesboolean表单输入值将保持不变。
keepDefaultValuesboolean保留通过 useForm 初始化的相同 defaultValues。
  • isDirty 将再次被检查:它被设置为将任何新提供的 value 与原始 defaultValues 进行比较的结果。
  • dirtyFields 将在提供 value 时再次被更新:它被设置为将新提供的 value 与原始 defaultValues 进行比较的结果。
keepIsSubmittedbooleanisSubmitted 状态将保持不变。
keepTouchedbooleanisTouched 状态将保持不变。
keepIsValidbooleanisValid 将暂时保留为当前状态,直到用户进行进一步操作。
keepSubmitCountbooleansubmitCount 状态将保持不变。
规则
  • 对于受控组件,您需要将 defaultValues 传递给 useForm 才能reset Controller 组件的值。

  • defaultValues 未传递给 reset API 时,将调用 HTML 原生 reset API 来恢复表单。

  • 避免在 useFormuseEffect 被调用之前调用 reset,因为 useForm 的订阅需要在 reset 可以发送信号以刷新表单状态更新之前准备就绪。

  • 建议在提交后在 useEffectreset

    useEffect(() => {
    reset({
    data: "test",
    })
    }, [isSubmitSuccessful])
  • 只要您在 useForm 中提供了 defaultValues,就可以在没有参数的情况下运行 reset

    reset(); // update form back to default values
    reset({ test: 'test' }); // update your defaultValues && form values
    reset(undefined, { keepDirtyValues: true }); // reset other form state but keep defaultValues and form values

示例


不受控

import { useForm } from "react-hook-form"
interface UseFormInputs {
firstName: string
lastName: string
}
export default function Form() {
const {
register,
handleSubmit,
reset,
formState: { errors },
} = useForm<UseFormInputs>()
const onSubmit = (data: UseFormInputs) => {
console.log(data)
}
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label>First name</label>
<input {...register("firstName", { required: true })} />
<label>Last name</label>
<input {...register("lastName")} />
<input type="submit" />
<input type="reset" value="Standard Reset Field Values" />
<input
type="button"
onClick={() => reset()}
value="Custom Reset Field Values & Errors"
/>
</form>
)
}
import React, { useCallback } from "react"
import { useForm } from "react-hook-form"
export default function App() {
const { register, handleSubmit, reset } = useForm()
const resetAsyncForm = useCallback(async () => {
const result = await fetch("./api/formValues.json") // result: { firstName: 'test', lastName: 'test2' }
reset(result) // asynchronously reset your form values
}, [reset])
useEffect(() => {
resetAsyncForm()
}, [resetAsyncForm])
return (
<form onSubmit={handleSubmit((data) => {})}>
<input {...register("firstName")} />
<input {...register("lastName")} />
<input
type="button"
onClick={() => {
reset(
{
firstName: "bill",
},
{
keepErrors: true,
keepDirty: true,
}
)
}}
/>
<button
onClick={() => {
reset((formValues) => ({
...formValues,
lastName: "test",
}))
}}
>
Reset partial
</button>
</form>
)
}

控制器

import React from "react"
import { useForm, Controller } from "react-hook-form"
import { TextField } from "@material-ui/core"
interface IFormInputs {
firstName: string
lastName: string
}
export default function App() {
const { register, handleSubmit, reset, setValue, control } =
useForm<IFormInputs>()
const onSubmit = (data: IFormInputs) => console.log(data)
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
render={({ field }) => <TextField {...field} />}
name="firstName"
control={control}
rules={{ required: true }}
defaultValue=""
/>
<Controller
render={({ field }) => <TextField {...field} />}
name="lastName"
control={control}
defaultValue=""
/>
<input type="submit" />
<input type="button" onClick={reset} />
<input
type="button"
onClick={() => {
reset({
firstName: "bill",
lastName: "luo",
})
}}
/>
</form>
)
}
import { useForm, Controller } from "react-hook-form"
import { TextField } from "@material-ui/core"
export default function App() {
const { register, handleSubmit, reset, setValue, control } = useForm()
const onSubmit = (data) => console.log(data)
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
render={({ field }) => <TextField {...field} />}
name="firstName"
control={control}
rules={{ required: true }}
defaultValue=""
/>
<Controller
render={({ field }) => <TextField {...field} />}
name="lastName"
control={control}
defaultValue=""
/>
<input type="submit" />
<input type="button" onClick={reset} />
<input
type="button"
onClick={() => {
reset({
firstName: "bill",
lastName: "luo",
})
}}
/>
</form>
)
}

提交并重置

import { useForm, useFieldArray, Controller } from "react-hook-form"
function App() {
const {
register,
handleSubmit,
reset,
formState,
formState: { isSubmitSuccessful },
} = useForm({ defaultValues: { something: "anything" } })
const onSubmit = (data) => {
// It's recommended to reset in useEffect as execution order matters
// reset({ ...data })
}
React.useEffect(() => {
if (formState.isSubmitSuccessful) {
reset({ something: "" })
}
}, [formState, submittedData, reset])
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("something")} />
<input type="submit" />
</form>
)
}

字段数组

import React, { useEffect } from "react"
import { useForm, useFieldArray, Controller } from "react-hook-form"
function App() {
const { register, control, handleSubmit, reset } = useForm({
defaultValues: {
loadState: "unloaded",
names: [{ firstName: "Bill", lastName: "Luo" }],
},
})
const { fields, remove } = useFieldArray({
control,
name: "names",
})
useEffect(() => {
reset({
names: [
{
firstName: "Bob",
lastName: "Actually",
},
{
firstName: "Jane",
lastName: "Actually",
},
],
})
}, [reset])
const onSubmit = (data) => console.log("data", data)
return (
<form onSubmit={handleSubmit(onSubmit)}>
<ul>
{fields.map((item, index) => (
<li key={item.id}>
<input {...register(`names.${index}.firstName`)} />
<Controller
render={({ field }) => <input {...field} />}
name={`names.${index}.lastName`}
control={control}
/>
<button type="button" onClick={() => remove(index)}>
Delete
</button>
</li>
))}
</ul>
<input type="submit" />
</form>
)
}

视频


感谢您的支持

如果您发现 React Hook Form 在您的项目中很有用,请考虑为其加星并提供支持。