如何从react-number-format库中获取数字值?

Alv*_*ani 3 reactjs react-number-format

我正在使用 React-number-format 库来格式化用户提供的输入。但由于某种原因,当我保存数据时,输入被保存为字符串而不是数字。这是默认行为吗?如果是,如何将其更改为数字,以便将格式化字符串保存为数字,并删除所有字符(例如 $、逗号等)?

这就是我使用它的方式。npm 包https://www.npmjs.com/package/react-number-format

               <NumberFormat
                    thousandSeparator={true}
                    prefix={"$"}
                    decimalScale={2}
                    fixedDecimalScale
                    disabled={isDisabled}
                 />
Run Code Online (Sandbox Code Playgroud)

Jor*_*Jor 6

您可以使用react-number-formats onValueChangeprop 来获取floatValuewhich 的类型number

它可以像这样使用:

  <NumberFormat
    {...someProps}
    onValueChange={(values) => {
      const {formattedValue, value, floatValue} = values;
      // do something with floatValue
    }}
  />
Run Code Online (Sandbox Code Playgroud)

来自文档:

formattedValue: '$23,234,235.56', //应用格式化后的值

value: '23234235.56', //非格式化值作为数字字符串 23234235.56,如果将此值设置为 state,请确保将 isNumericString 属性传递为 true

floatValue: 23234235.56 //浮点表示。对于大数字,它可以具有指数语法

有关更多信息,请参阅https://www.npmjs.com/package/react-number-format#values-object 。