7.51.2
将
react-hook-forms
useFormContext
与此组件一起使用时:
import { useFormContext } from "react-hook-form";
import { get } from "lodash";
export const TextInput = ({
name,
placeholder,
disabled = false,
}) => {
const { register, formState } = useFormContext();
const field = register(name, {
maxLength: { value: 5, message: "Too Long" },
});
const error = get(formState.errors, name);
const label = error ? <label>{error.message}</label> : null;
return (
<div>
<input
data-testid={`form-input-${name}`}
type="text"
autoComplete="off"
placeholder={placeholder}
readOnly={disabled}
{...field}
/>
{label}
</div>
);
};
正确包装在提供程序中(包装输入的
div
的样式已将其删除,以提高视觉清晰度):
import { FormProvider, useForm } from "react-hook-form";
import { TextInput } from "./TextInput";
import { Submit } from "./Submit";
export const Form = ({ onSubmit, initialValues }) => {
const methods = useForm({ defaultValues: initialValues });
const submitFunction = methods.handleSubmit(onSubmit);
return (
<FormProvider {...methods}>
<form onSubmit={submitFunction}>
<div>
<div>
<TextInput
name="name"
placeholder="Name"
/>
</div>
</div>
<Submit
onClick={submitFunction}
isFormValid={methods.formState.isValid}
/>
</form>
</FormProvider>
);
};
无论出于何种原因,
formState: {errors}
中的错误都不会更新onChange
/onBlur
/onFocus
。尽管验证返回无效时formState : {isValid}
会进行更新。
通过我的调查,我注意到如果我将更改处理程序更新为
const handleChange = async (e) => {
await trigger(fieldName)
await onChange(e)
}
哪里
onChange
和 trigger
来自 react-hook-form
。
然后错误对象就会正确更新。
我制作了一个代码沙箱来说明它:
https://codesandbox.io/p/sandbox/cool-lalande-8n2kxp
任何帮助让它工作而不需要破解它来强制手动验证触发的帮助,我们将不胜感激。也许我正在做的事情的结构在某个地方是错误的?老实说,我在这里不知所措。