
React 支持多语言国际化 -- i18next

前言
随着互联网应用的全球化发展,多语言支持(国际化,Internationalization,简称 i18n)成为现代前端开发中不可或缺的一部分。React 作为主流的前端框架,如何优雅地实现多语言切换?本文将以 i18next 这个流行的国际化库为例,详细讲解如何在 React 项目中实现多语言支持。
什么是 i18next?
i18next 是一个功能强大且灵活的国际化框架,支持多种前端和后端环境。它提供了语言资源管理、语言切换、占位符替换、格式化等丰富功能。配合 React 的绑定库 react-i18next,可以非常方便地在 React 应用中实现多语言。
准备工作
- 确保你有一个基于 React 的项目(使用 Create React App、Vite 或其他脚手架均可)
- 熟悉 React 基础知识
- 对 JavaScript 模块有基本了解
安装依赖
在项目根目录打开终端,执行以下命令安装 i18next 和 react-i18next:
bashnpm install i18next react-i18next
或使用 yarn:
bashyarn add i18next react-i18next
创建语言资源文件
语言资源文件是存放不同语言文本的 JSON 文件,通常按语言代码分类。
项目结构示例:
shellsrc/ locales/ en/ translation.json zh/ translation.json
en/translation.json(英文)
json{ "welcome": "Welcome to React", "description": "This is a simple internationalization example." }
zh/translation.json(中文)
json{ "welcome": "欢迎使用 React", "description": "这是一个简单的国际化示例。" }
初始化 i18next
在 src 目录下创建 i18n.js 文件,负责初始化 i18next。
javascriptimport i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; // 导入语言资源 import enTranslation from './locales/en/translation.json'; import zhTranslation from './locales/zh/translation.json'; i18n .use(initReactI18next) // 让 i18next 绑定 React .init({ resources: { en: { translation: enTranslation, }, zh: { translation: zhTranslation, }, }, lng: 'zh', // 默认语言 fallbackLng: 'en', // 如果当前语言资源不存在,回退到英文 interpolation: { escapeValue: false, // React 已经安全处理了 XSS }, }); export default i18n;
在 React 中使用 i18next
1. 在入口文件中引入 i18n
一般在 src/index.js 或 src/main.jsx 中引入:
javascriptimport React from 'react'; import ReactDOM from 'react-dom/client'; import App from './App'; import './i18n'; // 引入 i18n 配置 const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<App />);
2. 使用 useTranslation 钩子
在任何组件中,可以通过 useTranslation 获取翻译函数 t。
示例 App.js:
javascriptimport React from 'react'; import { useTranslation } from 'react-i18next'; function App() { const { t, i18n } = useTranslation(); // 切换语言函数 const changeLanguage = (lng) => { i18n.changeLanguage(lng); }; return ( <div style={{ padding: 20 }}> <h1>{t('welcome')}</h1> <p>{t('description')}</p> <button onClick={() => changeLanguage('en')}>English</button> <button onClick={() => changeLanguage('zh')}>中文</button> </div> ); } export default App;
进阶功能
1. 动态插值
i18next 支持动态变量替换,比如:
json{ "greeting": "Hello, {{name}}!" }
React 组件中:
javascript<p>{t('greeting', { name: 'Alice' })}</p>
输出:
shellHello, Alice!
2. 语言检测和持久化
可以集成 i18next-browser-languagedetector 插件,自动检测用户浏览器语言,提升体验。
安装:
bashnpm install i18next-browser-languagedetector
修改 i18n.js:
javascriptimport LanguageDetector from 'i18next-browser-languagedetector'; i18n .use(LanguageDetector) .use(initReactI18next) .init({ // ...其他配置 });
这样,i18next 会自动检测浏览器语言并使用。
3. 多命名空间支持
大型项目可能会将翻译拆分为多个命名空间,方便管理。
资源示例:
shelllocales/en/common.json locales/en/home.json
初始化时配置多个命名空间:
javascripti18n.init({ ns: ['common', 'home'], defaultNS: 'common', resources: { en: { common: { /* ... */ }, home: { /* ... */ }, }, zh: { common: { /* ... */ }, home: { /* ... */ }, }, }, });
使用时指定命名空间:
javascriptconst { t } = useTranslation('home');
总结
通过以上步骤,你已经掌握了如何在 React 项目中使用 i18next 实现多语言国际化:
- 安装并配置 i18next 和 react-i18next
- 准备语言资源文件
- 初始化 i18next,绑定 React
- 使用
useTranslation钩子实现文本翻译和语言切换 - 掌握动态插值、语言检测、多命名空间等进阶功能