React Hook Form:提交带有嵌套组件的表单或提取嵌套组件的字段进行提交

Ahm*_*med 25 javascript nested reactjs react-component react-hook-form

我有一个包含多个组件的表单(每个组件都是基于功能或基于类的组件),其中包含多个输入字段或单选按钮。当我提交表单时,我要么想要提交嵌套在组件中的字段以及表单数据,要么我应该能够提取字段数据然后提交它们(不确定哪种方法是最好的,为什么?)。我怎样才能实现这个目标?

代码 :

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

export default function TestComponent() {
  const { register, handleSubmit, errors } = useForm();
  const onSubmit = data => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label htmlFor="name">Name</label>
      <input type="text" id="name" name="name" ref={register({ required: true, maxLength: 30 })} />
      {errors.name && errors.name.type === "required" && <span>This is required</span>}
      {errors.name && errors.name.type === "maxLength" && <span>Max length exceeded</span> }
      <NestedComponent1 />
      <NestedComponent2 />
      <input type="submit" />
    </form>
  );
}

function NestedComponent1() {
    return (
        <div>
            <input type="text" id="nested-name" name="nestedName" />
            <input type="text" id="nested-name2" name="nestedName2" />
            <input type="text" id="nested-name3" name="nestedName3" />
        </div>
    );
}

function NestedComponent2() {
    return (
        <div>
            <input type="text" id="nested-comp2-name" name="nestedcomp2Name" />
            <input type="text" id="nested-comp2-name2" name="nestedcomp2Name2" />
            <input type="text" id="nested-comp2-name3 name="nestedcomp2Name3" />
        </div>
    );
}
Run Code Online (Sandbox Code Playgroud)

小智 25

您可以使用挂钩useFormContext来避免将上下文作为道具传递https://react-hook-form.com/api/useformcontext

您只需使用组件包装表单FormProvider,以便可以useFormContext在嵌套组件中使用上下文

export default function TestComponent() {
    const methods = useForm();
    const { register, handleSubmit, errors } = methods;
    const onSubmit = data => console.log(data);

    return (
    <FormProvider {...methods} > // pass all methods into the context
        <form onSubmit={handleSubmit(onSubmit)}>
        <label htmlFor="name">Name</label>
        <input type="text" id="name" name="name" ref={register({ required: true, maxLength: 30 })} />
        {errors.name && errors.name.type === "required" && <span>This is required</span>}
        {errors.name && errors.name.type === "maxLength" && <span>Max length exceeded</span> }
        <NestedComponent1 />
        <input type="submit" />
        </form>
    </FormProvider>
    );
}

function NestedComponent1() {
    const { register } = useFormContext(); // retrieve all hook methods
    
    return (
        <div>
            <input {...register("nestedName")} type="text" id="nested-name" name="nestedName"  />
            <input {...register("nestedName2")} type="text" id="nested-name2" name="nestedName2" />
            <input {...register("nestedName3")} type="text" id="nested-name3" name="nestedName3" />
        </div>
    );
}

Run Code Online (Sandbox Code Playgroud)


Yar*_*die 4

要从嵌套组件中提取数据,您可以在 TestComponent 中添加“useState”并将 onChange 函数传递给嵌套组件。

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

export default function App() {
  const { register, handleSubmit, errors } = useForm();
  const onSubmit = (data) => console.log(data);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label htmlFor="name">A</label>
      <input
        type="text"
        id="name"
        name="name"
        ref={register({ required: true, maxLength: 30 })}
      />
      {errors.name && errors.name.type === "required" && (
        <span>This is required</span>
      )}
      {errors.name && errors.name.type === "maxLength" && (
        <span>Max length exceeded</span>
      )}
      <NestedComponent1 register={register} />
      <NestedComponent2 register={register} />
      <input type="submit" />
    </form>
  );
}

function NestedComponent1({register}) {
  return (
    <div style={{ display: "flex", flexDirection: "column" }}>
      <label htmlFor="nestedName">B</label>
      <input type="text" id="nested-name" name="nestedName" ref={register} />
      <label htmlFor="nesteNamename2">C</label>
      <input type="text" id="nested-name2" name="nestedName2" ref={register} />
      <label htmlFor="nestedName3">D</label>
      <input type="text" id="nested-name3" name="nestedName3" ref={register} />
    </div>
  );
}

function NestedComponent2({ register }) {
  return (
    <div style={{ display: "flex", flexDirection: "column" }}>
      <label htmlFor="nestedcomp2Name">E</label>
      <input
        type="text"
        id="nested-comp2-name"
        name="nestedcomp2Name"
        ref={register}
      />
      <label htmlFor="nestedcomp2Name2">F</label>
      <input
        type="text"
        id="nested-comp2-name2"
        name="nestedcomp2Name2"
        ref={register}
      />
      <label htmlFor="nestedcomp2Name3">G</label>
      <input
        type="text"
        id="nested-comp2-name3"
        name="nestedcomp2Name3"
        ref={register}
      />
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

  • 我改变了我的答案,请检查上面。您所需要做的就是将注册方法发送给孩子们。另请查看react-hook-form的官方文档:https://react-hook-form.com/advanced-usage/ (2认同)