问题描述
我正在使用 react-number-format 库来格式化用户提供的输入。但出于某种原因,当我保存数据时,输入被保存为字符串而不是数字。这是默认行为吗?如果是,如何将其更改为数字,以便将格式化的字符串保存为数字并删除所有字符(例如 $、逗号等)?
这就是我使用它的方式。 npm 包 https://www.npmjs.com/package/react-number-format
<NumberFormat
thousandSeparator={true}
prefix={"$"}
decimalScale={2}
fixedDecimalScale
disabled={isdisabled}
/>
解决方法
您可以使用 react-number-format
的 onValueChange
属性来获取 floatValue
类型的 number
。
可以这样使用:
<NumberFormat
{...someProps}
onValueChange={(values) => {
const {formattedValue,value,floatValue} = values;
// do something with floatValue
}}
/>
来自文档:
formattedValue: '$23,234,235.56',//应用格式化后的值
value: '23234235.56',//非格式化值作为数字字符串 23234235.56,如果您将此值设置为状态,请确保将 isNumericString 属性传递为 true
floatValue: 23234235.56 //浮点数表示。对于大 数字可以有指数语法
有关详细信息,请参阅 https://www.npmjs.com/package/react-number-format#values-object。