【问题标题】:React - Format input field to show currency using Dinero.jsReact - 使用 Dinero.js 格式化输入字段以显示货币
【发布时间】:2020-10-05 09:47:09
【问题描述】:

我正在构建一个响应表单,其中包含一些需要用货币格式化的输入。所以需要以$为前缀,加上逗号、小数(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"                                        
/>

【问题讨论】:

  • 你不应该在handleChangeProductPrice1y函数中重新格式化数字吗?设置状态时也不需要async和await
  • @ludwiguer 你能把这个作为答案发布,如果它有效,我可以将它设置为正确答案

标签: javascript reactjs typescript forms


【解决方案1】:

这就是我会做的,离开不格式化的状态并在渲染中进行格式化

//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/react-currency-input 的库

编辑 2

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

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

【讨论】:

  • 它甚至不会加载应用程序
  • 啊,我明白了,有什么建议吗?顺便说一句,谢谢,
  • 其实我以前用过那个!我切换的原因是因为 Edge 浏览器不支持 react-currency-input,我需要它
  • @hisusu32 我编辑了答案,也许对你有帮助
【解决方案2】:

只是

<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"                                        
/>

应该可以。

这有帮助。

【讨论】:

  • 这甚至不允许我在输入中输入任何字符。不知道为什么
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多