格式化价格
显示本地化的货币和数字格式
问题
显示价格需要同时包含数字和货币。例如,美国的价格是 $1,200.50,而在德国相同的金额可能显示为 1 200,50 €。货币符号的位置、小数点分隔符和分组分隔符都会发生变化,为每种语言硬编码这些规则是不可行的。
解决方案
使用 react-intl 的 FormattedNumber 组件,并设置 style: 'currency' 选项。该组件会从其提供者读取当前的语言环境,并将数字格式化为价格,自动处理该语言环境和指定货币的符号位置、小数点分隔符和分组分隔符。
步骤
1. 创建一个用于显示价格的客户端组件
react-intl 的格式化组件必须在客户端组件中使用。
创建一个新组件,app/components/ProductPrice.tsx。
// app/components/ProductPrice.tsx
'use client';
import { FormattedNumber } from 'react-intl';
type Props = {
price: number;
currencyCode: string; // 例如 "USD", "EUR", "JPY"
};
export default function ProductPrice({ price, currencyCode }: Props) {
return (
<FormattedNumber
value={price}
style="currency"
currency={currencyCode}
/>
);
}
2. 传递格式化选项
FormattedNumber 组件通过以下属性进行控制:
value:价格的数值。style: 'currency':这告诉组件将数字格式化为货币,而不是标准的小数。currency:三字母 ISO 货币代码(例如 'USD', 'EUR')。当使用style: 'currency'时,这是必需的。
3. 在页面中使用该组件
现在,您可以在服务器或客户端组件中使用此组件来显示价格。
// app/[lang]/page.tsx
import ProductPrice from '@/app/components/ProductPrice';
export default function Home() {
const product = {
price: 1299.99,
currency: 'USD',
};
const productInEuros = {
price: 1199.5,
currency: 'EUR',
};
return (
<div>
<h1>产品</h1>
<p>
价格 (USD): <ProductPrice price={product.price} currencyCode={product.currency} />
</p>
<p>
价格 (EUR): <ProductPrice price={productInEuros.price} currencyCode={productInEuros.currency} />
</p>
</div>
);
}
访问 /en 的用户将看到 "价格 (USD): $1,299.99" 和 "价格 (EUR): €1,199.50"。访问 /es 的用户将看到 "价格 (USD): 1299,99 US$" 和 "价格 (EUR): 1199,50 €"。