[英]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"
/>
编辑
你在这里有两个问题:
编辑 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.