
react-intl 指南:设置 React 国际化
在 React 应用中设置 FormatJS react-intl,包括 IntlProvider、FormattedMessage、useIntl、ICU 消息格式和自动翻译。
改用 react-i18next? 查看 react-i18next 指南
安装 react-intl
react-intl 是 FormatJS 项目的一部分,提供 React 组件和 hook,并按 ICU MessageFormat 标准格式化字符串、数字、日期和复数。
npm install react-intl配置 IntlProvider
在根组件使用 IntlProvider 包装应用。传入当前语言和扁平 messages 对象,之后所有下级组件都可通过 FormattedMessage 或 useIntl 获取译文。
import React from 'react';
import ReactDOM from 'react-dom/client';
import { IntlProvider } from 'react-intl';
import App from './App';
import enMessages from './messages/en.json';
import deMessages from './messages/de.json';
const messages: Record<string, Record<string, string>> = {
en: enMessages,
de: deMessages,
};
// Detect locale from browser or your routing layer
const locale = navigator.language.split('-')[0] || 'en';
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<IntlProvider locale={locale} messages={messages[locale] || messages.en}>
<App />
</IntlProvider>
</React.StrictMode>
);消息文件
为每种语言创建一个 JSON 文件。react-intl 原生使用 ICU MessageFormat 语法,复数、select 和变量都以内联方式写在消息字符串中。
// messages/en.json
{
"app.greeting": "Hello, {name}!",
"nav.home": "Home",
"nav.about": "About",
"nav.settings": "Settings",
"cart.itemCount": "{count, plural, one {# item} other {# items}} in your cart"
}
// messages/de.json
{
"app.greeting": "Hallo, {name}!",
"nav.home": "Startseite",
"nav.about": "Über uns",
"nav.settings": "Einstellungen",
"cart.itemCount": "{count, plural, one {# Artikel} other {# Artikel}} in Ihrem Warenkorb"
}在组件中使用译文
react-intl 提供两个主要 API:用于渲染翻译 JSX 的 FormattedMessage 组件,以及用于命令式访问的 useIntl hook,例如占位文本、aria 标签和编程式格式化。
FormattedMessage 组件
在 JSX 中使用 FormattedMessage 进行声明式翻译。传入消息 ID 和插值值,它会直接渲染翻译字符串。
import { FormattedMessage } from 'react-intl';
function Greeting({ userName }: { userName: string }) {
return (
<div>
<h1>
<FormattedMessage
id="app.greeting"
values={{ name: userName }}
/>
</h1>
<nav>
<a href="/"><FormattedMessage id="nav.home" /></a>
<a href="/about"><FormattedMessage id="nav.about" /></a>
</nav>
</div>
);
}useIntl Hook
需要将译文作为普通值使用时,请调用 useIntl(),例如输入框占位文本、aria-label、document.title,或向非 React API 传递字符串。它还提供 formatNumber、formatDate 和 formatRelativeTime。
import { useIntl } from 'react-intl';
function SearchBar() {
const intl = useIntl();
return (
<input
type="search"
placeholder={intl.formatMessage({ id: 'search.placeholder' })}
aria-label={intl.formatMessage({ id: 'search.ariaLabel' })}
/>
);
}
// useIntl also gives you formatNumber, formatDate, formatRelativeTime:
function PriceTag({ amount, currency }: { amount: number; currency: string }) {
const intl = useIntl();
return (
<span>{intl.formatNumber(amount, { style: 'currency', currency })}</span>
);
}富文本(译文中的 HTML)
在消息字符串中使用类似 XML 的标签,将 JSX 嵌入译文。通过 values 属性传入标签处理程序,即可在翻译消息中渲染链接、粗体文本或任意 React 组件。
import { FormattedMessage } from 'react-intl';
// Message: "By signing up, you agree to our <link>Terms</link>."
// Key: "signup.terms"
// Value: "By signing up, you agree to our <link>Terms</link>."
function SignUp() {
return (
<FormattedMessage
id="signup.terms"
values={{
link: (chunks) => <a href="/terms" className="underline">{chunks}</a>,
}}
/>
);
}使用 @formatjs/cli 提取消息
FormatJS 提供 CLI,可自动从源代码提取消息 ID 到 JSON 文件。这样无需手动记录,也能让消息文件与组件保持同步。
# Install the CLI
npm install -g @formatjs/cli
# Extract messages from source code into a JSON file
formatjs extract 'src/**/*.tsx' --out-file messages/en.json --id-interpolation-pattern '[sha512:contenthash:base64:6]'
# Or use explicit IDs (recommended):
formatjs extract 'src/**/*.tsx' --out-file messages/en.json
# Compile messages for production (optional, improves perf)
formatjs compile messages/en.json --out-file compiled/en.json
formatjs compile messages/de.json --out-file compiled/de.json复数与 ICU Select
react-intl 原生使用 ICU MessageFormat。复数、基于性别的 select 和嵌套格式都直接写在消息字符串中,无需后缀约定或单独键。
// ICU MessageFormat syntax — react-intl uses this natively
// English
{
"cart.itemCount": "{count, plural, one {# item} other {# items}} in your cart",
"inbox.unread": "You have {count, plural, =0 {no unread messages} one {# unread message} other {# unread messages}}"
}
// Arabic — 6 plural forms
{
"cart.itemCount": "{count, plural, zero {لا عناصر} one {عنصر واحد} two {عنصران} few {# عناصر} many {# عنصرًا} other {# عنصر}} في سلتك"
}
// Japanese — 1 form (other)
{
"cart.itemCount": "カートに{count}個の商品があります"
}用于性别和角色的 ICU Select
对于性别、用户角色或状态值等依赖上下文的译文,请使用 ICU select 语法。select 表达式会根据提供的值选择正确变体。
// Gender-dependent messages using ICU select
{
"user.greeting": "{gender, select, male {He} female {She} other {They}} liked your post.",
"user.invitation": "{role, select, admin {You can manage all settings.} editor {You can edit content.} other {You can view content.}}"
}
// Usage:
<FormattedMessage
id="user.greeting"
values={{ gender: user.gender }}
/>自动保证翻译质量
常见问题
过度依赖 defaultMessage
使用嵌套对象而非扁平键
IntlProvider 导致重新渲染
测试中缺少 IntlProvider
推荐的文件结构
my-react-app/
├── messages/
│ ├── en.json # Source of truth (English)
│ ├── de.json # German
│ ├── ja.json # Japanese
│ └── es.json # Spanish
├── compiled/ # Optional: compiled messages for prod
│ ├── en.json
│ └── ...
├── src/
│ ├── main.tsx # App entry with IntlProvider
│ ├── App.tsx
│ └── components/
│ ├── Greeting.tsx # Uses FormattedMessage
│ └── SearchBar.tsx # Uses useIntl
└── package.json立即试用 i18n Agent
将翻译文件拖放到此处
JSON, YAML, PO, XML, CSV, Markdown, Properties
或点击选择文件
目标语言
使用 react-intl-locale-chain 实现语言回退
如果 pt-BR 等区域语言缺少翻译键,react-intl 会直接跳到默认语言,而不会先检查父语言 pt。
npm install react-intl-locale-chain<LocaleChainProvider
fallbacks={{
'pt-BR': ['pt', 'en'],
'zh-Hant-HK': ['zh-Hant', 'zh', 'en'],
}}
defaultLocale="en"
>
<App />
</LocaleChainProvider>查看语言回退指南,了解受支持框架的完整列表和 75 条内置回退链。 Learn more →