简体   繁体   English

如何使 react-hook-form 在一页中与多个 forms 一起工作?

[英]how to make react-hook-form work with multiple forms in one page?

I am using react-hook-form in my project and I have 2 totally separate forms, but when I submit one of the forms and if some fields in the other form is required I can't submit the current form, check the demo , and try to submit one of the form, the forms should work independently of each other but it looks like they depend on each other.我在我的项目中使用 react-hook-form 并且我有 2 个完全独立的 forms,但是当我提交其中一个 forms 并且如果需要其他表单中的某些字段时,我无法提交当前表单,请查看演示,并尝试提交其中一种表格,forms 应该彼此独立工作,但看起来它们相互依赖。

any help please?请问有什么帮助吗?

Welcome to StackOverflow @webcoder You are using the same hook instance for both forms.欢迎使用 StackOverflow @webcoder 您正在为两种表单使用相同的钩子实例。 You will have to reuse with different names.您将不得不使用不同的名称重复使用。

import React from "react";
import ReactDOM from "react-dom";
import { useForm } from "react-hook-form";

import "./styles.css";

function App() {
  const {
    register,
    formState: { errors },
    handleSubmit,
  } = useForm({
    mode: "onBlur",
  });

  const {
    register: register2,
    formState: { errors: errors2 },
    handleSubmit: handleSubmit2,
  } = useForm({
    mode: "onBlur",
  });

  const onSubmit = (data) => {
    alert(JSON.stringify(data));
  };

  const onSubmitEmail = (data) => {
    alert(JSON.stringify(data));
  };

  return (
    <div className="App">
      <form key={1} onSubmit={handleSubmit(onSubmit)}>
        <div>
          <label htmlFor="firstName">First Name</label>
          <input
            name="firstName"
            placeholder="bill"
            ref={register({ required: true })}
          />
          {errors.firstName && <p>This is required</p>}
        </div>

        <div>
          <label htmlFor="lastName">Last Name</label>
          <input
            name="lastName"
            placeholder="luo"
            ref={register({ required: true })}
          />
          {errors.lastName && <p>This is required</p>}
        </div>
        <input type="submit" />
      </form>

      <form key={2} onSubmit={handleSubmit2(onSubmitEmail)}>
        <div>
          <label htmlFor="email" placeholder="bluebill1049@hotmail.com">
            Email
          </label>
          <input name="email" ref={register2({ required: true })} />
          {errors2.email && <p>This is required</p>}
        </div>
        <input type="submit" />
      </form>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Quick update to Faizaan's answer: in my case, errors should be used with formState , not by itself.快速更新 Faizaan 的答案:在我的情况下, errors应该与formState一起使用,而不是单独使用。 Therefore, the property should be imported as:因此,该属性应导入为:

const { formState: { errors } } = useForm();
const { formState: { errors: errors2 } } = useForm();

The names might be confusing, but these is the solution that I arrived at.名称可能令人困惑,但这些是我得出的解决方案。

If someone is using useForm with other libraries like Material UI and have two forms then can be used:如果有人将 useForm 与 Material UI 等其他库一起使用并且有两个 forms 则可以使用:

const { control, handleSubmit } = useForm({
resolver: yupResolver(schema), })

const { control: control2, handleSubmit: handleSubmitReset } = useForm({
    resolver: yupResolver(schema2),
  });


  const onSubmit = async (data) => {
    console.log(data);
  };

 const onSubmitResend = async (data) => {
        console.log(data);
      };

And the forms will look like: forms 看起来像:

FORM-1 FORM-1

<form key={1} onSubmit={handleSubmitReset(onSubmitResend)}>
          <FormLabel
            component="legend"
            color="secondary"
            sx={{ color: "#fff", pt: 2 }}
          >
            Email:
          </FormLabel>
          <Controller
            defaultValue=""
            name="email"
            control={control2}
            render={({
              field: { onChange, value },
              fieldState: { error },
            }) => (
              <TextField
                helperText={error ? error.message : null}
                error={!!error}
                value={value}
                onChange={onChange}
                id="outlined-basic"
                placeholder="Enter Email address"
                variant="outlined"
                fullWidth
                color="secondary"
                InputProps={{
                  style: {
                    color: "#fff",
                    border: "1px solid #fff",
                    borderRadius: "32px",
                    marginTop: "16px",
                  },
                }}
              />
            )}
          />

          >
            <Button
              fullWidth
              color="secondary"
              type="submit">
               Submit
            </Button>
        </form>

FORM-2 FORM-2

 <form key={2} onSubmit={handleSubmit(onSubmit)}>
          <FormLabel
            component="legend"
            color="secondary"
            sx={{ color: "#fff", pt: 2 }}
          >
            Email:
          </FormLabel>
          <Controller
            defaultValue=""
            name="email"
            control={control}
            render={({
              field: { onChange, value },
              fieldState: { error },
            }) => (
              <TextField
                helperText={error ? error.message : null}
                error={!!error}
                value={value}
                onChange={onChange}
                id="outlined-basic"
                placeholder="Enter Email address"
                variant="outlined"
                fullWidth
                color="secondary"
                InputProps={{
                  style: {
                    color: "#fff",
                    border: "1px solid #fff",
                    borderRadius: "32px",
                    marginTop: "16px",
                  },
                }}
              />
            )}
          />

          >
            <Button
              fullWidth
              color="secondary"
              type="submit">
               Submit
            </Button>
        </form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM