我有一个字段数组,其中有一个输入字段,我为其设置了一些验证规则,例如 required 和 minLength。
我希望在附加新字段时立即验证该字段。但是,这种情况并没有发生,即使我附加空字段,这些输入字段的错误仍然未定义:
function App() {
const useFormMethods = useForm({
defaultValues: {
test: [{ firstName: "Bill", lastName: "Luo" }]
},
mode: "onChange"
});
const { fields, append, remove } = useFieldArray({
control: useFormMethods.control,
name: "test",
rules: {
minLength: 4
}
});
const onSubmit = (data) => console.log("data", data);
return (
<FormProvider {...useFormMethods}>
<form onSubmit={useFormMethods.handleSubmit(onSubmit)}>
<h1>Field Array </h1>
<span className="counter">Render Count: {renderCount}</span>
<ul>
{fields.map((item, index) => {
return (
<li key={item.id}>
<FormControlledInput name={`test.${index}.firstName`} />
<FormControlledInput name={`test.${index}.lastName`} />
<button type="button" onClick={() => remove(index)}>
Delete
</button>
</li>
);
})}
</ul>
<section>
<button
type="button"
onClick={() => {
append({ firstName: "", lastName: "" });
}}
>
append
</button>
</section>
<input type="submit" />
</form>
</FormProvider>
);
}
这是需要验证的受控输入:
export const FormControlledInput = ({ name }) => {
const {
control,
formState: { errors }
} = useFormContext();
const { field, fieldState } = useController({
name,
control,
rules: { required: true }
});
console.log(`fieldState error: `, fieldState.error);
console.log(`formState errors: `, errors);
return <input onChange={field.onChange} value={field.value} />;
};
您可以在此处查看工作代码和框示例。 我需要做什么才能使其在每次更改时得到验证?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
用于将字段添加到数组的
append方法是异步的,执行验证的trigger方法也是异步的,因此存在竞争条件,导致在向数组注册字段之前触发验证形式。在添加数组字段时触发重新验证之前,您可以只await该函数结果。我分叉了你的 CSB 这里。我还添加了一个
useEffect挂钩,该挂钩将在安装组件时触发验证。