第16章 国际化与多语言支持
使用React i18next进行多语言切换
1. 什么是国际化(i18n)?
国际化(Internationalization,简称i18n)是指设计和开发能够适应不同语言、地区和文化习惯的应用程序的过程。在React中,react-i18next是一个流行的国际化库,基于i18next生态系统,提供了强大的多语言支持能力。
2. 安装与基础配置
安装依赖
npm install i18next react-i18next i18next-browser-languagedetector
初始化i18n
在项目中创建i18n.js配置文件:
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
// 多语言资源文件
const resources = {
en: {
translation: {
welcome: "Welcome",
button: "Click me"
}
},
zh: {
translation: {
welcome: "欢迎",
button: "点击我"
}
}
};
i18n
.use(LanguageDetector) // 自动检测浏览器语言
.use(initReactI18next)
.init({
resources,
fallbackLng: 'en', // 默认语言
interpolation: {
escapeValue: false // React已经处理XSS防护
}
});
export default i18n;
3. 在组件中使用翻译
函数组件示例
import { useTranslation } from 'react-i18next';
function Welcome() {
const { t, i18n } = useTranslation();
return (
<div>
<h1>{t('welcome')}</h1>
<button onClick={() => i18n.changeLanguage('zh')}>
切换到中文
</button>
</div>
);
}
类组件示例
import { withTranslation } from 'react-i18next';
class Welcome extends React.Component {
render() {
const { t } = this.props;
return <h1>{t('welcome')}</h1>;
}
}
export default withTranslation()(Welcome);
4. 高级功能
命名空间(Namespaces)
// 配置
i18n.init({
ns: ['common', 'dashboard'],
defaultNS: 'common'
});
// 使用
t('dashboard:title');
插值(Interpolation)
// 资源定义
{
"greeting": "Hello, {{name}}!"
}
// 使用
t('greeting', { name: 'John' });
复数形式(Plurals)
// 资源定义
{
"itemCount": "{{count}} item",
"itemCount_plural": "{{count}} items"
}
// 使用
t('itemCount', { count: 5 }); // 输出"5 items"
5. 最佳实践
- 分离语言文件:将不同语言的翻译维护在单独的JSON文件中
- 按需加载:使用
i18next-http-backend动态加载语言包 - 持续集成:将翻译文件与专业翻译平台(如Crowdin)集成
- 测试覆盖:确保所有动态文本都有翻译键值
6. 常见问题解决
- 动态内容翻译:使用
Trans组件处理包含HTML的翻译 - 语言切换延迟:预加载语言包
- 缺失翻译:配置
saveMissing选项记录缺失的键
提示:
react-i18next还支持服务端渲染(SSR)和React Native环境,配置方式与客户端类似。
