React.js - 受控输入toLocaleString()

时间:2018-03-14 10:59:54

标签: javascript reactjs

我想获得一串数字并添加逗号,以便为长数字创建更易读的格式。通常情况下,我会使用ctx.font = "12pt arial"; ctx.fillText("Today, however, the Scottish contributed", 10, 20); ctx.scale(3, 3); ctx.font = "4pt arial"; ctx.fillText("Today, however, the Scottish contributed", 10/3, 20); ,但它无法按预期使用受控输入。

在我的代码中我正在做:

toLocaleString()

在输入3个号码后重置字段 - 任何想法?

https://codesandbox.io/s/91q75k22mo

2 个答案:

答案 0 :(得分:2)

工作解决方案 - 在你的handleChange函数中,改变它:

const toNumber = Number(event.target.value);

到此:

const toNumber = Number(event.target.value.replace(/\D/g, ''));

它无法工作的原因是因为它根据输入值创建了Number,这不是普通数字而是格式化字符串。因此它包含非数字字符。以上只是删除了非数字字符(虽然现在您知道问题还有其他方法可以解决它)。

答案 1 :(得分:0)

您可以使用FormattedNumber中的react-intl。该文档可在此处获取:https://github.com/yahoo/react-intl/wiki/Components#number-formatting-components

样本:

<IntlProvider locale='en'>
  <FormattedNumber value={examples.negativeNumber} />
</IntlProvider>
相关问题