You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+TS搭配Formik使用withFormik HOC时报Type '{}'不可赋值给IProps如何解决?

报错原因

Type '{}' is not assignable to type 'IProps'. Type '{}' is missing the following properties from type 'FormikState': values, errors, touched, isSubmitting, and 2 more.

  • 核心原因是withFormik高阶组件的泛型参数使用错误:Formik官方定义的withFormik泛型顺序为withFormik<外部传入属性类型, 表单值类型>,你错误将内部组件需要的带Formik注入属性的IProps作为了第一个泛型参数,导致TypeScript认为你使用LoginView组件时需要主动传入所有Formik内置属性(values、errors等),而你调用时没有传任何参数,触发类型不匹配报错。
  • 没有拆分内外属性类型:你定义的IProps继承了FormikProps,这部分属性是withFormik内部自动注入给包裹的Login组件的,不需要外部传入,不能用作外层组件的入参类型。
修复方案

按以下步骤修改代码即可解决问题:

  1. 拆分属性类型定义,区分外层传入属性和内层组件接收属性:
// 原有表单值类型保留
interface FormValues {
  email?:string,
  password?:string
}
// 外层调用LoginView时传入的属性,当前不需要额外传参就定义为空对象
interface OuterProps {}
// 内层Login组件接收的属性 = 外层传入属性 + Formik自动注入的属性
interface InnerProps extends OuterProps, FormikProps<FormValues> {}
  1. 修正withFormik的泛型参数,将第一个泛型替换为外层属性OuterProps:
export const LoginView = withFormik<OuterProps, FormValues>({
  enableReinitialize: true,
  // 这里的props就是外层传入的OuterProps类型
  mapPropsToValues: (props) => {
    console.log(props);
    return { email: "", password: "" };
  },
  validationSchema: Yup.object({
    // 可后续补充校验规则
  }),
  handleSubmit: (values) => {
    console.log(values);
  },
})(Login);
  1. 调整Login组件的props类型为内层属性InnerProps:
const Login: React.FC<InnerProps> = (props) => {
  // 原有组件逻辑保持不变即可
}
额外优化提示

你当前代码里的表单输入控件没有绑定Formik的状态和事件,输入内容不会同步到Formik的values中,建议给每个TextField补充绑定:

<TextField
  variant="outlined"
  margin="normal"
  required
  fullWidth
  id="email"
  label="Email Address"
  name="email"
  autoFocus
  // 补充以下绑定
  value={props.values.email}
  onChange={props.handleChange}
  onBlur={props.handleBlur}
  error={Boolean(props.errors.email && props.touched.email)}
  helperText={props.touched.email && props.errors.email}
/>

同时form标签要替换为Formik提供的Form组件,或者给form的onSubmit绑定props.handleSubmit,否则提交事件不会触发Formik的提交逻辑。

内容的提问来源于stack exchange,提问作者RRR uzumaki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 07:42:01