Pep*_*Pep 5 number-formatting reactjs material-ui
我的团队目前正在使用 React-number-format 包和 Material UI 来格式化和屏蔽需要格式化的数字。为此,我们使用 Material UI 文本字段的 InputComponent。
https://material-ui.com/components/text-fields/
我遇到过一种情况,从 API 获取的数据是小数,但用户希望以百分比形式与其进行交互。
例如:0.1201 在字段中应显示为 12.01%
用户应该能够以百分比形式编辑字段,但数据必须再次以小数形式发送回 API。
例如:字段从 12.01% 更改为 15.01%,但该值应存储为 0.1501。
我知道如何在 JavaScript 中将小数转换为分数,但我很难将值转换为百分比以进行显示,然后再转换回小数以进行存储。
有没有办法用反应数字格式来做到这一点?如果没有,有没有办法用 Material UI 的 TextField 来做到这一点?
是的,你可以使用react-number-format来做到这一点。
由于您可以完全控制<NumberFormat />with propsvalue和onValueChange,因此在处理函数中给出值*100并设置值/100就可以了。
const onValueChangeHandler = (event: NumberFormatValues) => {
// event.floatValue / 100
// use the `floatValue` rather than `formattedValue`
}
<NumberFormat
suffix={'%'}
decimalScale={2}
value={value * 100}
onValueChange={onValueChangeHandler}
/>;
Run Code Online (Sandbox Code Playgroud)
参考:
NumberFormat事件接口
export interface NumberFormatValues {
floatValue: number | undefined;
formattedValue: string;
value: string;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15890 次 |
| 最近记录: |