如何在antd Form.Item中自动获取react-number-format的floatValue?
解决antd Form自动获取react-number-format的floatValue最优方案
核心思路
把react-number-format的NumericFormat封装成符合antd Form字段规范的自定义组件,让Form直接绑定floatValue,无需手动维护state和提交时替换值。
具体实现
1. 封装可复用的数字输入组件
import { NumericFormat } from 'react-number-format'; import type { InputProps } from 'antd'; // 定义组件属性,继承antd Input的属性并扩展数字格式化配置 interface NumericInputProps extends InputProps { thousandSeparator?: string; decimalSeparator?: string; decimalScale?: number; prefix?: string; fixedDecimalScale?: boolean; } const NumericInput = ({ value, onChange, thousandSeparator = ".", decimalSeparator = ",", decimalScale = 2, prefix = "R$", fixedDecimalScale = true, ...rest }: NumericInputProps) => { // 将格式化后的floatValue传递给antd Form的onChange const handleValueChange = (values: { floatValue: number | null; formattedValue: string }) => { onChange?.(values.floatValue ?? undefined); }; // 将Form传递的数字值格式化为显示用的字符串 const displayValue = value !== undefined && value !== null ? new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL', minimumFractionDigits: decimalScale, maximumFractionDigits: decimalScale, }).format(value) : ''; return ( <NumericFormat value={displayValue} onValueChange={handleValueChange} thousandSeparator={thousandSeparator} decimalSeparator={decimalSeparator} decimalScale={decimalScale} prefix={prefix} fixedDecimalScale={fixedDecimalScale} {...rest} /> ); }; export default NumericInput;
2. 在antd Form中使用该组件
无需手动维护state,Form会自动收集floatValue作为字段值:
import { Form, Button } from 'antd'; import NumericInput from './NumericInput'; const MyForm = () => { const onFinish = async (values: { fator: number }) => { // 直接使用Form收集的floatValue,无需手动替换 await doRegister(values); }; return ( <Form initialValues={{ fator: 123.45 }} // 初始值可以直接传数字 onFinish={onFinish} > <Form.Item label="My label" name="fator"> <NumericInput /> </Form.Item> <Form.Item> <Button type="primary" htmlType="submit">提交</Button> </Form.Item> </Form> ); };
方案优势
- 减少重复代码:不用每个数字字段都写
onValueChange和维护单独的state - 自动双向绑定:Form的初始值会自动格式化为带前缀的字符串显示,输入时自动把
floatValue传回Form - 提交直接使用:Form收集的就是最终需要的数字值,无需提交时手动替换字段
内容的提问来源于stack exchange,提问作者Rodrigo Lobo
相关产品推荐
相关产品推荐

