You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用formatjs实现多语言场景下的复数化翻译?

FormatJS 实现支持国际化的复数化方案

核心逻辑

FormatJS 基于 ICU 消息语法实现,天然内置全球不同语言的复数规则,无需手动编写单复数判断逻辑,可完美适配多语言场景下的复数化消息需求。

实现步骤

1. 定义带复数语法的国际化词条

你可以按照不同语言的翻译需求,直接在对应的语言包中定义带复数标识的词条:

中文语言包示例

{
  "selectedItems": "{count, plural, =0 {0 项已选} one {1 项已选} other {# 项已选}}"
}

英文语言包示例

{
  "selectedItems": "{count, plural, =0 {0 items Selected} one {1 item Selected} other {# items Selected}}"
}

语法说明:

  • count:对应你代码中传入的数量变量,也就是你原来的numberSelected
  • plural:声明当前消息使用复数格式化规则
  • =0:精确匹配数值为0的特殊场景
  • one/other:对应对应语言的单/复数规则,FormatJS 会根据当前 locale 自动适配规则,无需手动判断
  • #:自动替换为传入的count数值

如果你需要适配你原来代码中的formattedType动态类型变量,可以把词条改成动态参数形式:

{
  "selectedCount": "{count, plural, =0 {0 {type}已选} one {1 {type}已选} other {# {type}已选}}"
}

2. 代码中调用格式化方法

React 项目(react-intl)调用示例

import { useIntl } from 'react-intl';

function YourComponent() {
  const intl = useIntl();
  const numberSelected = 2; // 你的选中数量变量
  // 如果不需要动态type直接调用即可
  const selectedText = intl.formatMessage({ id: 'selectedItems' }, { count: numberSelected });
  // 如果需要动态type,传入翻译后的type参数即可
  // const selectedText = intl.formatMessage({ id: 'selectedCount' }, { count: numberSelected, type: intl.formatMessage({ id: 'item' }) });
  return <div>{selectedText}</div>
}

原生 JS 项目调用示例

import { createIntl, createIntlCache } from '@formatjs/intl';

const cache = createIntlCache();
const intl = createIntl({
  locale: 'zh-CN', // 可动态切换为当前使用的语言,如en-US
  messages: {
    selectedItems: '{count, plural, =0 {0 项已选} one {1 项已选} other {# 项已选}}'
  }
}, cache);

const numberSelected = 1;
console.log(intl.formatMessage({ id: 'selectedItems' }, { count: numberSelected }));
// 输出:1 项已选

方案优势

  • 天然适配多语言:不同语言的复数规则无需手动维护,FormatJS 会根据当前 locale 自动适配,例如法语0属于单数范畴、俄语存在三类复数形式等场景,无需修改业务代码,仅调整对应语言的翻译词条即可生效
  • 避免硬编码拼接问题:无需手动拼接字符串,可适配不同语言的语序差异,解决硬拼接{pluralize(...)} Selected无法适配部分语言数量后置等语序需求的问题

内容的提问来源于stack exchange,提问作者kastaplastislife

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 23:09:03