使用 Yup 的 react-hook-form 解析器类型错误

kev*_*vin 8 reactjs react-hook-form

我正在创建一个身份验证表单,并参考react-hook-form文档了解如何使用 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;
Run Code Online (Sandbox Code Playgroud)

Nea*_*arl 7

这看起来像是一个库错误,将@hookform/resolvers降级似乎2.8.0可以解决该问题。

Codesandbox 演示

编辑:2.8.1您可以通过强制yubResolver使用通用来消除版本上的错误yub.AnyObjectSchema。感谢 Mihai-github解决了这个问题。

useForm<IFormInputs>({
  resolver: yupResolver<yup.AnyObjectSchema>(schema),
});
Run Code Online (Sandbox Code Playgroud)

Codesandbox 演示