我正在创建一个身份验证表单,并且我正在引用react-hook-form docs,了解如何使用 yup 来验证我的输入。据我所知,一切都与文档中提供的实现几乎相同。但是,我在
useForm
解析器上收到错误(如下所示)。知道我哪里出错了吗?
"react-hook-form": "^7.15.2"
"yup": "^0.32.9"
"@hookform/resolvers": "^2.8.1"
interface IFormInputs {
email: string;
password: string;
passwordConfirm: string;
}
const schema = yup.object().shape({
email: yup.string().required(),
password: yup.string().required(),
passwordConfirm: yup.string().required(),
});
const SignUp = (): JSX.Element => {
const {
control,
handleSubmit,
getValues,
formState: { errors },
} = useForm<IFormInputs>({ resolver: yupResolver(schema) });
const onSubmit: SubmitHandler<IFormInputs> = () => {
const values = getValues();
console.log('values', values);
};
return (
<div>
<StyledPaper>
<StyledTypography>Sign Up</StyledTypography>
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
name="email"
rules={{ required: 'this field is required' }}
defaultValue=""
control={control}
render={({ field }) => (
<TextField
fullWidth
label="Email"
variant="filled"
value={field.value}
error={!!errors.email}
helperText="Provide an email"
{...field}
/>
)}
/>
<StyledButton type="submit">Submit</StyledButton>
</form>
</StyledPaper>
<div>
<StyledTypography>Already have an account? Log in.</StyledTypography>
</div>
</div>
);
};
export default SignUp;
这看起来像是一个库错误,将 @hookform/resolvers 降级为
2.8.0
似乎可以解决该问题。
编辑: 您可以通过强制
2.8.1
使用 yubResolver
通用来删除版本 yub.AnyObjectSchema
上的错误。感谢
Mihai-github 来解决这个问题。
useForm<IFormInputs>({
resolver: yupResolver<yup.AnyObjectSchema>(schema),
});
您可以像这样修复它们:
resolver: yupResolver<yup.AnyObject>(schema),
useForm<IFormInputs>({
resolver: yupResolver<IFormInputs>(schema),
});
无需添加任何
Yup Schema type
,只需将useForm<interface/type>
传递给yupResolver<interface/type>
即可。
注意。确保架构应包含与
interface/type
相同的键
以上答案都不适合我。我不想像 NearHuscarl 所说的那样将
@hookform/resolvers
降级到 2 年以上版本。解决方法是在错误发生之前在该行添加 // @ts-expect-error ts(2322)
来消除错误。在你的情况下,在行之前
resolver: yupResolver(schema),
。这将使打字稿忽略该错误。