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

标签 reactjs react-hook-form

我想访问嵌套组件中 react-hook-form 的 Resister 中定义的验证规则,以动态显示所需的指标 (*)。
有没有办法从嵌套组件访问?
我不想通过作为 Prop 传递来重复。

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

最佳答案

看看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} />;
}
它允许您访问嵌套组件级别的所有钩子(Hook)表单方法。

关于reactjs - react-hook-form 访问嵌套组件中的验证规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64733410/

相关文章:

javascript - 如何访问 Yup 模式中的上下文

javascript - React-hook-form 验证不适用于自定义字段数组

reactjs - 带有react-draft-wysiwyg的react-hook-form Controller

node.js - 如何在 react 应用程序中重新加载每个页面时停止 firebase re-auth()?

jquery - 在react componentDidMount中bind(this)后获取jquery对象

reactjs - 无法获取react-hook-form中的值表单输入

javascript - react-hook-form 多步表单问题

javascript - 使用 setInterval 函数和 React 卡住 Chrome

javascript - React JS : Explanation of this. props.items.map 功能

javascript - 简单的 react 计数器