react-number-format与Formik、MUI配合失效,表单提交报错
解决react-number-format + MUI TextField + Formik 无法获取值的问题
问题核心:react-number-format的customInput与Formik的useField结合时,未正确将格式化后的数值同步到Formik状态,导致提交时返回空字符串,触发必填验证错误。
解决步骤:
- 修改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;
- 调整初始值类型(可选但推荐)
由于Yup验证的是数字类型,将初始值设为数字而非空字符串,避免类型不匹配:
const FORM_STATE = { price: 0 // 替换原有的空字符串 };
- 确保NumericFormat的属性配置正确
保留原有格式化配置,无需额外修改NumericFormat组件,customInput会通过修改后的FieldWrapper正确处理值同步:
<NumericFormat thousandSeparator="," allowNegative={false} decimalScale={2} decimalSeparator="." fixedDecimalScale={true} customInput={TextField} {...priceProps} />
修改完成后,Formik可正确获取react-number-format输入的数字值,提交时不会出现空字符串,且能通过Yup的必填验证。
内容的提问来源于stack exchange,提问作者Luft
相关产品推荐
相关产品推荐

