我想访问嵌套组件中 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/