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

Rat*_*oni 6 multiple-forms reactjs 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,
});
Run Code Online (Sandbox Code Playgroud)

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

小智 8

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

    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: {},
  });
Run Code Online (Sandbox Code Playgroud)


Nit*_*iya 4

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

const { handleSubmit, errors, control, reset } = useForm({
    mode: "onSubmit",
    reValidateMode: "onChange",
    defaultValues: "",
    validateCriteriaMode: "all",
    submitFocusError: true,
    nativeValidation: false,
});
    
const {
  handleSubmit: handleSubmit1,
  errors: errors1,
  control: control1,
  reset: reset1,
} = useForm({
  mode: "onSubmit",
  reValidateMode: "onChange",
  defaultValues: "",
  validateCriteriaMode: "all",
  submitFocusError: true,
  nativeValidation: false,
});
Run Code Online (Sandbox Code Playgroud)

现在基本上你可以在渲染函数下创建两种形式,如下所示

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

  <form
    form
    onSubmit={handleSubmit1(onProfileChange)}
    noValidate
    autoComplete="off"
  >
    {/* Reference "error1" and "control1" variable to validate your form fields */}
  </form>
</>;
Run Code Online (Sandbox Code Playgroud)

现在,您可以在同一页面上通过react-hook-form验证两种不同的表单,而无需处理太多状态变量。