最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React.js - Controlled input toLocaleString() - Stack Overflow

programmeradmin1浏览0评论

I want to get a string of numbers and add mas 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.

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?

I want to get a string of numbers and add mas 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.

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?

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

Share Improve this question asked Mar 14, 2018 at 10:59 Paul RedmondPaul Redmond 3,2964 gold badges35 silver badges53 bronze badges 1
  • I think this is like an issue of react. github./facebook/react/issues/6368 – Heartbit Commented Mar 14, 2018 at 11:27
Add a ment  | 

2 Answers 2

Reset to default 5

Working solution - in your handleChange function, change this:

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. 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. The documentation is available here: https://github./yahoo/react-intl/wiki/Components#number-formatting-ponents

A sample:

<IntlProvider locale='en'>
  <FormattedNumber value={examples.negativeNumber} />
</IntlProvider>
发布评论

评论列表(0)

  1. 暂无评论