react-hook-form访问嵌套组件中的验证规则

时间:2020-11-07 23:25:43

标签: reactjs react-hook-form

我想访问嵌套组件中react-hook-form的Resister中定义的验证规则,以动态显示所需的指标(*)。 有没有办法从嵌套组件进行访问?

我不想通过作为道具重复。

<TextBox ref={register({ required: true })} label="Serial No" name="serialNo" />

const TextBox = React.forwardRef(({ label, name }, ref) => (
    <>
        <label htmlFor={name}>
            {label} {***required*** && <span>*</span>}
        </label>
        <input type="text" name={name} id={name} ref={ref} />
    </>
))

1 个答案:

答案 0 :(得分:1)

看看https://react-hook-form.com/api#useFormContext

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

export default function App() {
  const methods = useForm();
  const onSubmit = data => console.log(data);

  return (
    <FormProvider {...methods} > // pass all methods into the context
      <form onSubmit={methods.handleSubmit(onSubmit)}>
        <NestedInput />
        <input type="submit" />
      </form>
    </FormProvider>
  );
}

function NestedInput() {
  const { register } = useFormContext(); // retrieve all hook methods
  return <input name="test" ref={register} />;
}

允许您访问嵌套组件级别中的所有钩子窗体方法。