react-intl - React-intl 自定义格式化程序
问题描述
有没有办法为 React-intl 传递自定义格式化程序?我看到<IntlProvider>
有一个formats
道具,但是查看FormatJS的文档,看起来这只允许扩充现有的格式化程序(例如number
,date
)。我当前的用例是一个名称列表,我想让它用逗号分隔,最后一个项目用连词(例如Steve, Joe, Sandra, Judith and Jerry
)连接。理想情况下,我只需传入一个列表 ( ['Steve', 'Joe', 'Sandra', 'Judith', 'Jerry']
),格式化程序就会为该语言使用适当的连接形式。目前支持吗?
解决方案
我认为您可以使用内置的选择格式化程序来实现这一点,如下所示:
const names = ['Steve', 'Joe', 'Sandra', 'Judith', 'Jerry'];
intl.formatMessage({id: 'layout'}, {
names: names.map((name, index) => intl.formatMessage(
{id: 'name'}, {
name: name,
position: index === names.length - 1 ?
'last' : (index === 0 ? 'first' : 'inner')
}
)).join('')
});
在您的翻译 JSON 文件中:
{
"layout": "Here are the names: {names}",
"name": "{position, select, first {} last {\u00a0and } other {, }}{name}"
}
这将允许您更改有关位置的分隔符(考虑到某些语言是从右到左阅读的)。只是连接所有“join('')
分隔符感知”名称来构建枚举字符串。
请注意,我使用 unicode\u00a0
字符作为空格,因为如果将通常的空格放在插值字符串的第一个位置,则会被忽略。
推荐阅读
- c++ - std::vector 的复制构造函数使用哪个分配器来分配内存?
- c++ - 如果互斥锁已被锁定, pthread_mutex_lock(pthread_mutex_t *mutex); 怎么办?阻塞线程并同时返回一个值?
- c# - 如何在基于 ASP.NET Core 5 的多层 Web 应用程序中初始化 AutoMapper?
- python - 找不到数据库文件
- teradata - Teradata Geospatial - 创建多多边形/多边形表
- facebook - 使用 Google Tag Manager 服务器端实现 Facebook Conversions API
- docker - LXC 容器内的 docker 服务:无法应用 RC_ULIMIT 设置
- react-native - 400 bad request axios react native
- docker - 自动卡住时如何使docker容器重新启动?
- r - 给定 R 中列表的输入,将数据帧转换为字符串