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

react-number-format与Formik、MUI配合失效,表单提交报错

解决react-number-format + MUI TextField + Formik 无法获取值的问题

问题核心:react-number-format的customInput与Formik的useField结合时,未正确将格式化后的数值同步到Formik状态,导致提交时返回空字符串,触发必填验证错误。

解决步骤:

  1. 修改FieldWrapper组件,适配react-number-format的onChange事件
    react-number-format的onChange会返回包含floatValue(原始数字值)和value(格式化后字符串)的对象,需将数字值传递给Formik的状态更新函数。

更新Input.jsx中的FieldWrapper:

import * as React from "react";
import TextField from "@mui/material/TextField";
import { useField } from "formik";

export const FieldWrapper = ({ name, onChange, ...otherProps }) => {
  const [field, meta] = useField(name);
  
  const handleChange = (event) => {
    // 处理react-number-format的特殊onChange返回值
    if (event?.floatValue !== undefined) {
      field.onChange(event.floatValue);
    } else {
      field.onChange(event);
    }
  };

  if (meta && meta.touched && meta.error) {
    otherProps.error = true;
    otherProps.helperText = meta.error;
  }

  const configText = {
    ...field,
    ...otherProps,
    fullWidth: true,
    variant: "outlined",
    onChange: onChange || handleChange
  };

  return <TextField {...configText} />;
};

export default FieldWrapper;
  1. 调整初始值类型(可选但推荐)
    由于Yup验证的是数字类型,将初始值设为数字而非空字符串,避免类型不匹配:
const FORM_STATE = {
  price: 0 // 替换原有的空字符串
};
  1. 确保NumericFormat的属性配置正确
    保留原有格式化配置,无需额外修改NumericFormat组件,customInput会通过修改后的FieldWrapper正确处理值同步:
<NumericFormat
  thousandSeparator=","
  allowNegative={false}
  decimalScale={2}
  decimalSeparator="."
  fixedDecimalScale={true}
  customInput={TextField}
  {...priceProps}
/>

修改完成后,Formik可正确获取react-number-format输入的数字值,提交时不会出现空字符串,且能通过Yup的必填验证。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 15:25:22