列表格式化
在处理项目列表时,可以将它们格式化为连词或选择词。
格式化方面,如所用的分隔符,会因地区而异:
- 在
en-US中为 “HTML, CSS, and JavaScript” - 在
de-DE中为 “HTML, CSS und JavaScript”
列表格式化可以通过 useFormatter 钩子应用:
import {useFormatter} from 'next-intl';
function Component() {
const format = useFormatter();
const items = ['HTML', 'CSS', 'JavaScript'];
// 渲染 "HTML, CSS, and JavaScript"
format.list(items, {type: 'conjunction'});
// 渲染 "HTML, CSS, or JavaScript"
format.list(items, {type: 'disjunction'});
}参见 MDN 文档关于 ListFormat 以了解更多关于你可以传给 list 函数的选项,或尝试 交互式浏览器 来体验 Intl.ListFormat。
注意,目前列表只能通过 useFormatter 来格式化,消息中暂无等效的内联语法。
要在多个组件间重用列表格式,可以配置 全局格式。
如何渲染消息数组?
请参见 消息数组指南。
React 元素的格式化
除了字符串值之外,你还可以将 React 元素数组传递给格式化函数:
import {useFormatter} from 'next-intl';
function Component() {
const format = useFormatter();
const users = [
{id: 1, name: 'Alice'},
{id: 2, name: 'Bob'},
{id: 3, name: 'Charlie'}
];
const items = users.map((user) => (
<a key={user.id} href={`/user/${user.id}`}>
{user.name}
</a>
));
return <p>{format.list(items)}</p>;
}结果:
<p>
<a href="/user/1">Alice</a>, <a href="/user/2">Bob</a>, and
<a href="/user/3">Charlie</a>
</p>注意在这种情况下,format.list 将返回一个 Iterable<ReactElement>。