在 React Hook Form 中设置默认值

Set default values in React Hook Form

如果用户使用 isDirty 参数修改了表单值,我想签入 RHF。

手动设置默认值有效:

const {handleSubmit, control, setValue, setError, setFocus} = useForm({defaultValues: {name: ""}});

这似乎工作正常。

但是当用户尝试编辑表单时,我使用 setValue 将值加载到表单中。

现在我不知道如何以编程方式设置默认值。

我就是这样做的,但答案并不正确。值已设置,但默认值不会以这种方式更改,因此 RHF 无法比较。

Make sure to provide all inputs' defaultValues at the useForm, so hook form can have a single source of truth to compare whether the form is dirty.

https://react-hook-form.com/api/useform/formstate

如何动态设置默认值,使其甚至可以在 'edit' 模式下工作?

使用 reset() 设置表单的 defaultValue 会更容易。这是我为您准备的 CodeSandbox 示例。

您所要做的就是在 useEffect() 中创建一个对象。使用该对象设置所有默认值。最后在 reset().

中传播那个 defaultValues 对象
  useEffect(() => {
    let defaultValues = {};
    defaultValues.firstName = "Kristof";
    defaultValues.lastName = "Rado";
    reset({ ...defaultValues });
  }, []);

  <input {...register("firstName")} placeholder="First Name" />
  <input {...register("lastName")} placeholder="Last Name" />