react 实现国际化
使用 react-i18next 实现国际化
react-i18next 是基于 i18next 的 React 国际化库,提供完整的国际化解决方案
安装依赖包:
npm install i18next react-i18next i18next-http-backend i18next-browser-languagedetector
创建 i18n 配置文件(i18n.js):
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: 'en',
debug: true,
interpolation: {
escapeValue: false,
}
});
export default i18n;
创建语言资源文件
在 public 目录下创建 locales 文件夹,结构如下:
public/
locales/
en/
translation.json
zh/
translation.json
示例英文翻译文件(en/translation.json):
{
"welcome": "Welcome to our application",
"changeLanguage": "Change language"
}
在组件中使用翻译
使用 useTranslation hook:
import React from 'react';
import { useTranslation } from 'react-i18next';
function MyComponent() {
const { t, i18n } = useTranslation();
const changeLanguage = (lng) => {
i18n.changeLanguage(lng);
};
return (
<div>
<h1>{t('welcome')}</h1>
<button onClick={() => changeLanguage('en')}>English</button>
<button onClick={() => changeLanguage('zh')}>中文</button>
</div>
);
}
使用 Trans 组件处理复杂翻译
对于包含 HTML 或变量的复杂翻译:
import { Trans } from 'react-i18next';
function ComplexComponent() {
return (
<Trans i18nKey="complexText">
This is a <strong>complex</strong> text with <a href="#">link</a>
</Trans>
);
}
对应的翻译文件需要:
{
"complexText": "This is a <1>complex</1> text with <2>link</2>"
}
服务端渲染支持
对于 Next.js 等 SSR 框架,需要额外配置:
import { I18nextProvider } from 'react-i18next';
import i18n from './i18n';
function MyApp({ Component, pageProps }) {
return (
<I18nextProvider i18n={i18n}>
<Component {...pageProps} />
</I18nextProvider>
);
}
命名空间支持
对于大型项目可以使用命名空间分隔翻译:
i18n.init({
ns: ['common', 'home', 'about'],
defaultNS: 'common'
});
使用命名空间翻译:
const { t } = useTranslation('home');
t('home:welcome');
动态加载语言包
优化性能可以按需加载语言包:
i18n.use(Backend).init({
backend: {
loadPath: '/locales/{{lng}}/{{ns}}.json'
}
});






