首页 > 解决方案 > 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} />
    </>
))

标签: reactjsreact-hook-form

解决方案


看看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} />;
}

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


推荐阅读