react 实现多语言
实现多语言支持的步骤
安装依赖库
使用 react-i18next 和 i18next 库实现多语言功能。安装命令如下:
npm install react-i18next i18next
配置语言文件
创建语言资源文件,例如 en.json(英文)和 zh.json(中文),存放在 src/locales 目录下。
示例 en.json:
{
"welcome": "Welcome to our app!",
"button": {
"submit": "Submit"
}
}
示例 zh.json:
{
"welcome": "欢迎使用我们的应用!",
"button": {
"submit": "提交"
}
}
初始化 i18n
在 src/i18n.js 中配置 i18next:
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import enTranslation from './locales/en.json';
import zhTranslation from './locales/zh.json';
i18n.use(initReactI18next).init({
resources: {
en: { translation: enTranslation },
zh: { translation: zhTranslation }
},
lng: 'en', // 默认语言
fallbackLng: 'en',
interpolation: { escapeValue: false }
});
export default i18n;
在 React 组件中使用
通过 useTranslation Hook 或 withTranslation HOC 实现多语言切换。
示例组件:
import React from 'react';
import { useTranslation } from 'react-i18next';
function App() {
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>
<button>{t('button.submit')}</button>
</div>
);
}
export default App;
动态加载语言包
对于大型应用,可以按需加载语言包以减少初始加载时间:
i18n.use(initReactI18next).init({
lng: 'en',
fallbackLng: 'en',
interpolation: { escapeValue: false },
backend: {
loadPath: '/locales/{{lng}}.json'
}
});
使用命名空间
拆分语言文件为多个命名空间(如 common.json、dashboard.json):
i18n.init({
ns: ['common', 'dashboard'],
defaultNS: 'common',
resources: {
en: {
common: { /* 翻译内容 */ },
dashboard: { /* 翻译内容 */ }
}
}
});
在组件中指定命名空间:
const { t } = useTranslation('dashboard');
服务端渲染支持
在 Next.js 等框架中,可通过 next-i18next 库简化配置:
npm install next-i18next
在 next.config.js 中配置:
const { i18n } = require('./next-i18next.config');
module.exports = { i18n };
创建 next-i18next.config.js:
module.exports = {
i18n: {
locales: ['en', 'zh'],
defaultLocale: 'en'
}
};






