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

如何获取Formik Context的validationSchema?为何返回undefined?

Formik中useFormikContext无法获取validationSchema的问题

我遇到一个问题:useFormikContext()的返回结果里始终拿不到validationSchema,虽然TypeScript类型定义里这个属性是可选存在的,但实际取值一直是undefined。

我写了一个接收fieldName的通用组件,原本想通过useFormikContext()拿到表单的validationSchema,如果存在的话,就从中提取对应字段的max()校验规则来赋值给maxLength(当组件没传入maxLength时)。

代码如下:

const MyComp = ({ fieldName, maxLength, ...props }) => {
  // validationSchema始终为undefined
  const { validationSchema } = useFormikContext();

  if (maxLength == null && validationSchema) {
    // 永远不会执行到这里
    maxLength = Yup.reach(validationSchema, fieldName)
      ?.tests.find(t => t.OPTIONS.name === 'max')
      ?.OPTIONS.params.max;
  }

  return (
    <div>
      The maxLength of <code>{fieldName}</code> length is{' '}
      <code>{maxLength ?? 'undefined'}</code>.
      {'\n'}
      Its <code>validationSchema</code> via{' '}
      <code>useFormikContext()</code> is{' '}
      <b>{ 
        validationSchema === null ? 'null' : 
        validationSchema ? 'definied' : 
        'not defined'
      }</b>.
    </div>
  );
};

const schema = Yup.object({
  withoutMaxLength: Yup.string(),
  withMaxLength: Yup.string().max(10),
  withMaxLengthProp: Yup.string()
});

const initialValues = {
  withoutMaxLength: "",
  withMaxLength: "",
  withMaxLengthProp: ""
};

const App = () => (
  <Formik
    initialValues={initialValues}
    onSumbit={() => {}}
    validationSchema={schema}
  >
    <Form>
      <MyComp fieldName="withoutMaxLength" />
      <MyComp fieldName="withMaxLength" />
      <MyComp fieldName="withMaxLengthProp" maxLength={10} />
    </Form>
  </Formik>
);

运行结果
运行结果

可以看到,即便在<Formik />组件中明确设置了validationSchema,useFormikContext().validationSchema还是一直是undefined。请问这是什么原因,该怎么解决?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 20:24:23