[英]React.js - Controlled input toLocaleString()
I want to get a string of numbers and add commas to create a more readable format for a long number. 我想获取一串数字并添加逗号以为长号创建更具可读性的格式。 Normally I'd use
toLocaleString()
but it's not working as expected with a controlled input. 通常我会使用
toLocaleString()
但是在受控输入下它无法正常工作。
In my code I'm doing: 在我的代码中,我正在做:
handleChange(event) {
const parseNumber = parseInt(event.target.value);
const toLocale = parseNumber.toLocaleString();
this.setState({ value: toLocale });
}
It's resetting the field after 3 numbers are entered - any ideas? 输入3个数字后,它将重置该字段-有什么想法吗?
https://codesandbox.io/s/91q75k22mo https://codesandbox.io/s/91q75k22mo
Working solution - in your handleChange function, change this: 工作解决方案-在您的handleChange函数中,更改以下内容:
const toNumber = Number(event.target.value);
to this: 对此:
const toNumber = Number(event.target.value.replace(/\D/g, ''));
The reason it wasn't working was because it was creating a Number
based on the input value, which isn't a plain number but a formatted string. 它不起作用的原因是因为它基于输入值创建了一个
Number
,它不是纯数字,而是带格式的字符串。 Hence it contains non-digit characters. 因此,它包含非数字字符。 The above just removes the non-digit characters (though now you know the issue there are other ways you could solve it).
上面的代码只是删除了非数字字符(尽管现在您知道了这个问题,还有其他方法可以解决)。
You can use FormattedNumber
from react-intl
. 您可以使用
react-intl
FormattedNumber
。 The documentation is available here: https://github.com/yahoo/react-intl/wiki/Components#number-formatting-components 该文档位于此处: https : //github.com/yahoo/react-intl/wiki/Components#number-formatting-components
A sample: 一个样品:
<IntlProvider locale='en'>
<FormattedNumber value={examples.negativeNumber} />
</IntlProvider>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.