首页 > 解决方案 > React-intl 自定义格式化程序

问题描述

有没有办法为 React-intl 传递自定义格式化程序?我看到<IntlProvider>有一个formats道具,但是查看FormatJS的文档,看起来这只允许扩充现有的格式化程序(例如numberdate)。我当前的用例是一个名称列表,我想让它用逗号分隔,最后一个项目用连词(例如Steve, Joe, Sandra, Judith and Jerry)连接。理想情况下,我只需传入一个列表 ( ['Steve', 'Joe', 'Sandra', 'Judith', 'Jerry']),格式化程序就会为该语言使用适当的连接形式。目前支持吗?

标签: react-intl

解决方案


我认为您可以使用内置的选择格式化程序来实现这一点,如下所示:

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字符作为空格,因为如果将通常的空格放在插值字符串的第一个位置,则会被忽略。


推荐阅读