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

Formik Field组件的FieldInputProps<string>与ShadCN Input OTP组件兼容异常问题

Formik Field组件的FieldInputProps与ShadCN Input OTP组件兼容异常问题

我之前也碰到过Formik和ShadCN组件适配的类似坑,咱们先把问题根因捋清楚,再给你直接能用的解决方案~

核心问题其实是回调参数格式不匹配:Formik的field.onChange默认期望接收的是标准的React ChangeEvent对象,而ShadCN的InputOTP组件的onChange回调返回的是纯字符串值(就是你输入的完整OTP码),不是事件对象。这就导致你直接传{...field}或者onChange={field.onChange}时,Formik根本识别不了这个参数,自然不会更新otp字段的值。

那怎么解决呢?直接绕开Formik默认的事件解析逻辑,手动用Formik提供的field.setValue方法来同步值就好,这是最直接的适配方式:

具体代码示例

<Field name="otp" component={({ field, ...props }: { field: FieldInputProps<string> }) => (
  <InputOTP
    maxLength={6}
    pattern={REGEXP_ONLY_DIGITS}
    // 手动把InputOTP返回的纯值传给Formik的setValue
    onChange={(value) => field.setValue(value)}
    // 同步Formik字段的值到InputOTP
    value={field.value}
    {...props}
  >
    <InputOTPGroup>
      <InputOTPSlot index={0} />
      <InputOTPSlot index={1} />
      <InputOTPSlot index={2} />
      <InputOTPSlot index={3} />
      <InputOTPSlot index={4} />
      <InputOTPSlot index={5} />
    </InputOTPGroup>
  </InputOTP>
)} />

如果你用children写法的话,逻辑也是一样的

<Field name="otp">
  {({ field }) => (
    <InputOTP
      maxLength={6}
      pattern={REGEXP_ONLY_DIGITS}
      onChange={(value) => field.setValue(value)}
      value={field.value}
    >
      <InputOTPGroup>
        {[0,1,2,3,4,5].map(i => <InputOTPSlot key={i} index={i} />)}
      </InputOTPGroup>
    </InputOTP>
  )}
</Field>

额外小提示

要是你担心输入格式的问题,InputOTP本身的pattern属性已经能配合限制输入了,只要保证value和onChange的映射是对的,Formik的字段就能实时同步更新。

备注:内容来源于stack exchange,提问作者Sourabrata Bose

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.13 17:13:14