
React 國際化完整指南
從零到多語言:在 React 應用程式中設定 i18n,再利用 AI 自動翻譯。
安裝套件
你需要三個套件:react-i18next(React 綁定)、i18next(核心庫),以及用於自動檢測語言的可選套件 i18next-browser-languagedetector。
npm install react-i18next i18next i18next-browser-languagedetector i18next-http-backend設定 i18n 實例
建立 i18n 設定檔案,使用預設語言、翻譯資源和外掛程式鏈初始化 i18next。必須在任何元件渲染前,於應用程式入口點匯入此檔案。
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import Backend from 'i18next-http-backend';
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next) // Must come before .init()
.init({
fallbackLng: 'en',
debug: process.env.NODE_ENV === 'development',
interpolation: {
escapeValue: false, // React already escapes
},
backend: {
loadPath: '/locales/{{lng}}/{{ns}}.json',
},
});
export default i18n;使用 I18nextProvider 包裝應用程式
在應用程式根目錄匯入 i18n 設定檔案,並使用 I18nextProvider 包裝元件樹。否則,useTranslation() 會傳回原始鍵而非譯文。
import React, { Suspense } from 'react';
import ReactDOM from 'react-dom/client';
import { I18nextProvider } from 'react-i18next';
import i18n from './i18n'; // Import your config
import App from './App';
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<Suspense fallback={<div>Loading...</div>}>
<I18nextProvider i18n={i18n}>
<App />
</I18nextProvider>
</Suspense>
</React.StrictMode>
);建立翻譯檔案
為每種語言建立一個 JSON 檔案。使用嵌套鍵按功能或頁面組織字串,並將來源語言(通常是英語)作為單一可信源。
// public/locales/en/translation.json
{
"nav": {
"home": "Home",
"about": "About",
"settings": "Settings"
},
"greeting": "Hello, {{name}}!",
"cart": {
"itemCount_one": "{{count}} item",
"itemCount_other": "{{count}} items"
}
}
// public/locales/de/translation.json
{
"nav": {
"home": "Startseite",
"about": "Über uns",
"settings": "Einstellungen"
},
"greeting": "Hallo, {{name}}!",
"cart": {
"itemCount_one": "{{count}} Artikel",
"itemCount_other": "{{count}} Artikel"
}
}在元件中使用譯文
在任何元件中呼叫 useTranslation() 取得 t() 函數。它可用於簡單字串、插值變數,以及通過 Trans 元件嵌入 JSX 的譯文。
import { useTranslation } from 'react-i18next';
function Greeting({ userName }: { userName: string }) {
const { t } = useTranslation();
return (
<div>
<h1>{t('greeting', { name: userName })}</h1>
<nav>
<a href="/">{t('nav.home')}</a>
<a href="/about">{t('nav.about')}</a>
</nav>
</div>
);
}import { Trans, useTranslation } from 'react-i18next';
// For JSX inside translations:
// "terms": "By signing up, you agree to our <link>Terms</link>."
function SignUp() {
const { t } = useTranslation();
return (
<Trans i18nKey="terms" components={{
link: <a href="/terms" className="underline" />
}} />
);
}處理複數和變數
i18next 按 CLDR 規則而非簡單的單數/複數處理。阿拉伯語有 6 種形式(zero、one、two、few、many、other),日語只有 1 種(other)。請在翻譯檔案中定義所有必需形式,i18next 會自動選擇正確形式。
// English: 2 forms (one, other)
{
"itemCount_one": "{{count}} item",
"itemCount_other": "{{count}} items"
}
// Arabic: 6 forms (zero, one, two, few, many, other)
{
"itemCount_zero": "لا عناصر",
"itemCount_one": "عنصر واحد",
"itemCount_two": "عنصران",
"itemCount_few": "{{count}} عناصر",
"itemCount_many": "{{count}} عنصرًا",
"itemCount_other": "{{count}} عنصر"
}
// Japanese: 1 form (other)
{
"itemCount_other": "{{count}}個のアイテム"
}新增語言切換與檢測
構建呼叫 i18n.changeLanguage() 的語言選擇器,並結合瀏覽器語言檢測器,在首次訪問時自動檢測用戶的首選語言,隨後儲存用戶的明確選擇。
import { useTranslation } from 'react-i18next';
const LANGUAGES = [
{ code: 'en', label: 'English' },
{ code: 'de', label: 'Deutsch' },
{ code: 'ja', label: '日本語' },
{ code: 'es', label: 'Español' },
];
function LanguageSwitcher() {
const { i18n } = useTranslation();
return (
<select
value={i18n.language}
onChange={(e) => i18n.changeLanguage(e.target.value)}
>
{LANGUAGES.map(({ code, label }) => (
<option key={code} value={code}>{label}</option>
))}
</select>
);
}自動翻譯
完成 i18n 設定後,使用 AI 翻譯本地化檔案。在 IDE 中讓 AI 助手翻譯來源檔案,或在 CI/CD 管線中使用 i18n Agent CLI。
# In your IDE, ask your AI assistant:
> Translate public/locales/en/translation.json to German, Japanese, and Spanish
✓ de/translation.json created (1.2s)
✓ ja/translation.json created (1.5s)
✓ es/translation.json created (1.1s)
# Or use the CLI in CI/CD:
npx i18n-agent translate public/locales/en/translation.json --lang de,ja,es自動保證翻譯質素
常見問題
譯文顯示原始鍵
缺少回退時發生 Suspense 錯誤
SSR 水合不匹配
翻譯鍵沒有自動補全
推薦的檔案結構
my-react-app/
├── public/
│ └── locales/
│ ├── en/
│ │ ├── translation.json # Default namespace
│ │ ├── common.json # Shared strings
│ │ └── dashboard.json # Feature namespace
│ ├── de/
│ │ ├── translation.json
│ │ ├── common.json
│ │ └── dashboard.json
│ └── ja/
│ └── ...
├── src/
│ ├── i18n.ts # i18n configuration
│ ├── main.tsx # App entry with Provider
│ ├── App.tsx
│ └── components/
│ └── LanguageSwitcher.tsx
└── package.json立即試用 i18n Agent
將翻譯檔案拖放到此處
JSON, YAML, PO, XML, CSV, Markdown, Properties
或點擊選擇檔案
目標語言