简体   繁体   English

React.js-LocalLocalString()的受控输入

[英]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.

相关问题 React.JS Typescript - OnChange 表示状态对象的“组件正在将类型文本的受控输入更改为在 OnChange 中不受控制” - React.JS Typescript - OnChange says "A component is changing a controlled input of type text to be uncontrolled in OnChange" for State Object 警告:组件正在将文本类型的受控输入更改为不受控制。 (React.js) - Warning: A component is changing a controlled input of type text to be uncontrolled. (React.js) React.js 使用嵌套状态控制组件 - React.js controlled components using nested states React.js-专注于清除受控textarea初始值 - React.js - Clear controlled textarea initial value on focus React.js控制文本光标焦点问题 - React.js controlled text cursor focus issue 如何在React.js的Edit阶段管理动态控制的表单? - How to manage a dynamically controlled form in Edit stage in react.js? 使用非状态变量时的React.js由于组件正在更改要控制的文本类型的不受控制的输入而导致错误 - React.js when using non state variable Getting error as A component is changing an uncontrolled input of type text to be controlled React.js输入性能 - React.js input performance 警告:组件正在将受控输入更改为反应 js 中的不受控输入 - Warning: A component is changing a controlled input to be uncontrolled input in react js 清除空输入中的数据-React.js - Clear data on empty input - React.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM