繁体   English   中英

React - 使用 Dinero.js 格式化输入字段以显示货币

[英]React - Format input field to show currency using Dinero.js

我正在构建一个反应表单,它有一些需要用货币格式化的输入。 所以它需要以$为前缀,添加逗号,小数(2 个小数点)。

我发现这个库叫做dinerojs.com : https://dinerojs.com/

我不确定我做错了什么,但这不是格式化。 该字段的工作方式与现在一样,但没有格式。 有任何想法吗?

//State
ProductPrice1: number,

//Set inital state
ProductPrice1: Dinero({ amount: 0 }).toFormat('$0,0.00'),

//handle bind
this.handleChangeProductPrice1  = this.handleChangeProductPrice1.bind(this);

//Change function
handleChangeProductPrice1y = async (event: any) => {
    const value = parseFloat(event.target.value)
    await this.setState({ ProductPrice1: value });      
}

//in my render
<input
    value={this.state.ProductPrice1}
    onChange={this.handleChangeProductPrice1}
    type="number"
    className="phone validate"
    name="ProductPrice1"                                        
/>

这就是我要做的,让 state 不格式化,并在渲染中进行格式化

//State
ProductPrice1: number,

//Set inital state
ProductPrice1: 0,

//handle bind
this.handleChangeProductPrice1  = this.handleChangeProductPrice1.bind(this);

//Change function
handleChangeProductPrice1y = (event: any) => {
    const value = parseFloat(event.target.value)
    this.setState({ ProductPrice1: value });      
}

//in my render
<input
    value={Dinero({ amount: this.state.ProductPrice1 }).toFormat('$0,0.00')}
    onChange={this.handleChangeProductPrice1}
    type="number"
    className="phone validate"
    name="ProductPrice1"                                        
/>

编辑

你在这里有两个问题:

  1. 您需要将输入的类型设置为文本,因为如果您使用数字,它将不接受格式
  2. 我检查了 Dinero 文档,没有办法将已经格式化的数量再次转换为数字,所以 parseFloat 不起作用,我认为你需要寻找另一个像这样的库https://www.npmjs.com/package/反应货币输入

编辑 2

也许你可以让它替换字符( $ ,. )所以你只保留这样的数字

  handleChangeProductPrice = (event: any) => {
    const value = event.target.value;
    const number = value.replace(/\$|,|\./g, "");
    setProductPrice(parseInt(number, 10));
  };

只是

<input
    value={this.state.ProductPrice1}
    onChange={(event) => this.setState({ ProductPrice1: Dinero({ amount: event.target.value }).toFormat('$0,0.00') })}
    type="number"
    className="phone validate"
    name="ProductPrice1"                                        
/>

应该管用。

跳这有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM