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} />
</>
))
解决方案
看看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} />;
}
它允许您访问嵌套组件级别中的所有钩子表单方法。
推荐阅读
- c# - Unity 2D代码在手机中重复但在电脑中没有问题
- firebase - 我的 Flutter Web 在本地构建得很好,但在 Firebase 托管中不起作用
- phpstorm - 如何在 PhpStorm 中为 Harp.js 命令行命令“harp compile”设置文件观察器?
- amazon-cognito - 如何配置 Cognito 以获取 Facebook 登录以传回包含的图片 url?
- angular - 取消选中Angular的ngx-datatable中的复选框
- javascript - 让 React Bootstrap 表单出现在同一行
- javascript - 空间复杂度中的 O(1) 与 O(n)
- python - Python数据框根据具有条件的另一列分配值
- mysql - 在 ubuntu 20.04 中恢复 mysql
- sql - ORA-00920: 准备好的语句的无效关系运算符错误