【问题标题】:react-hook-form resolver type error using Yup使用 Yup 的 react-hook-form 解析器类型错误
【发布时间】:2021-11-15 04:37:37
【问题描述】:

我正在创建一个身份验证表单,我正在参考 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;

【问题讨论】:

    标签: reactjs react-hook-form


    【解决方案1】:

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

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

    useForm<IFormInputs>({
      resolver: yupResolver<yup.AnyObjectSchema>(schema),
    });
    

    【讨论】:

    • Attempted import error: 'AnyObjectSchema' is not exported from 'yup' (imported as 'yup') 显示此错误,该怎么办? @Nearhuscarl
    • @ShubhamSinghvi 你用的是什么yup/resolver版本?
    • @hookform/resolvers@2.8.4 yup@0.32.11 react-hook-form@7.20.5 是。
    猜你喜欢
    • 2021-10-04
    • 2022-01-25
    • 2021-11-05
    • 1970-01-01
    • 2021-09-23
    • 2021-10-05
    • 2022-01-23
    • 2021-04-10
    • 2021-02-04
    相关资源
    最近更新 更多