使用 react-hook-form 在同一页面上添加两个表单

Adding two forms on the same page with react-hook-form

我是 REACT-HOOK-FORM 的新手。我创建了一个个人资料页面,我需要在其中创建两个单独的表单。一次用于“更改密码”,另一次用于“配置文件更改”。我正在努力通过 REACT-HOOK-FORM 创建两个单独的表单并利用它来提供验证。

const { handleSubmit, errors, control, reset, setValue } = useForm({
mode: "onSubmit",
reValidateMode: "onChange",
defaultValues: "",
validateCriteriaMode: "all",
submitFocusError: true,
nativeValidation: false,
});

我需要对上面的代码进行一些修改吗?请帮忙。

您需要按以下方式创建“useForm”的副本

const { handleSubmit, errors, control, reset } = useForm({
  mode: "onSubmit",
  reValidateMode: "onChange",
  defaultValues: "",
  validateCriteriaMode: "all",
  submitFocusError: true,
  nativeValidation: false,
});

const { handleSubmit1, errors1, control1, reset1 } = useForm({
  mode: "onSubmit",
  reValidateMode: "onChange",
  defaultValues: "",
  validateCriteriaMode: "all",
  submitFocusError: true,
  nativeValidation: false,
});

现在基本上您可以在渲染函数下创建两个表单,如下所示

<form onSubmit={handleSubmit(onProfileChange)} noValidate autoComplete="off">
{{Reference "error" and "control" variable to validate your form fields}}
</form>

<form onSubmit={handleSubmit(onProfileChange)} noValidate autoComplete="off">
{{Reference "error1" and "control1" variable to validate your form fields}}
</form>

现在您可以在同一个页面上有两个不同的表单,由 REACT-HOOK-FORMS 验证,而无需手动处理太多的 STATE 变量。

这是正确答案。看看我是如何解构对象的

    const {
    register,
    handleSubmit,
    watch,
    errors,
    setValue,
    setError,
    control,
    formState: { isSubmitting, isValid },
  } = useForm({
    resolver: yupResolver(schema()),
    mode: "onTouched",
    defaultValues: {},
  });


    const {
    register:register1,
    handleSubmit:handleSubmit1,
    watch:watch1,
    errors:errors1,
    setValue:setValue1,
    setError:setError1,
    control:control1,
  } = useForm({
    resolver: yupResolver(schema1()),
    mode: "onTouched",
    defaultValues: {},
  });