javascript 如何让react-hook-form在一个页面中处理多个表单?

l5tcr1uw  于 2023-03-28  发布在  Java
关注(0)|答案(3)|浏览(161)

我在我的项目中使用react-hook-form,我有两个完全独立的表单,但是当我提交其中一个表单时,如果另一个表单中的某些字段是必需的,我无法提交当前表单,请检查demo,并尝试提交其中一个表单,表单应该相互独立工作,但看起来它们相互依赖。

t9aqgxwy

t9aqgxwy1#

您正在为两个表单使用相同的钩子示例。您将不得不使用不同的名称来重用。

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);
wswtfjt7

wswtfjt72#

快速更新Faizaan的回答:在我的例子中,errors应该与formState一起使用,而不是单独使用。因此,属性应该导入为:

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

这些名字可能会让人感到困惑,但这是我得出的解决方案。

68de4m5k

68de4m5k3#

如果有人将useForm与其他库(如Material UI)一起使用,并且有两个表单,则可以使用:

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);
      };

这些表单将如下所示:
表格-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>

表格-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>

相关问题