货币
<Currency> 组件 API 参考
概述
<Currency> 组件会将数值按货币格式渲染。
数字将根据当前 locale 以及传入的可选参数进行格式化。
该组件仅负责格式化,不进行任何汇率换算。
<Currency>{100}</Currency>
// 输出:$100.00所有重新格式化均在本地进行,使用 Intl.NumberFormat 库实现。
参考
Props
Prop
Type
描述
| Prop | 描述 |
|---|---|
children | 要在组件内部渲染的内容。通常是表示需要格式化为货币的数值。若提供,则优先于 value 属性生效。 |
name | 可选的货币字段名称,用于元数据。 |
value | 货币的默认值。若未提供,则回退至 children。可为字符串或数字。字符串会在格式化前解析为数字。 |
currency | 货币类型,例如“USD”或“EUR”。用于确定货币符号和格式。 |
options | 可选的货币格式化 options,遵循 Intl.NumberFormatOptions 规范。使用它来定义最大小数位、分组等样式。 |
locales | 可选的 locales,用于指定格式化所用的 locale。若未提供,将使用用户的默认 locale。关于指定 locales 的更多信息参见此处。 |
返回值
一个 JSX.Element,其中包含格式化后的货币字符串。
示例
基本示例
<Currency> 组件可用于显示本地化的货币金额。
import { Currency } from 'gt-next';
export default function PriceDisplay(item) {
return (
<Currency> {item.price} </Currency>
);
}指定货币
这里我们将价格显示为欧元。
import { Currency } from 'gt-next';
export default function PriceDisplay(item) {
return (
<Currency currency="EUR"> {item.price} </Currency>
);
}翻译 <Currency> 组件
假设你希望在一段也会被翻译的句子中显示货币。
你可以将 <Currency> 组件包裹在 <T> 组件中。
import { T, Currency } from 'gt-next';
export default function PriceDisplay(item) {
return (
<T id="itemPrice">
价格为 <Currency> {item.price} </Currency>。
</T>
);
}自定义格式
此处我们以 GBP 显示价格,精确指定小数位数,并使用该货币的窄符号(即显示为“$100”而非“US$100”)。 在此阅读 Intl.NumberFormatOptions 以了解更多可用选项。
import { Currency } from 'gt-next';
export default function PriceDisplay(item) {
return (
<Currency
currency="GBP"
options={{
currencyDisplay: 'narrowSymbol',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}}
>
{item.price}
</Currency>
);
}注意事项
<Currency>组件用于根据当前locale和传入的可选参数对货币value进行格式化。- 该组件仅负责格式化,不进行任何汇率换算。
<Currency>组件的内容不会发送到 API 进行翻译。 所有重新格式化均在本地通过Intl.NumberFormat库完成。
后续步骤
- 如需了解
<Currency>组件及<Num>、<DateTime>、<Var>等其他变量组件的更多详情与使用示例,
本指南如何?