在 React 应用中实现国际化(i18n)可以使用多种方法和库。最常用的库之一是 react-i18next
,它是 i18next
的一个 React 绑定库。下面是一个使用 react-i18next
实现国际化的示例步骤:
1. 安装依赖
首先,安装必要的包:
1npm install i18next react-i18next i18next-http-backend i18next-browser-languagedetector
2. 配置 i18next
在你的项目中创建一个 i18n.js
文件,并进行以下配置:
1import i18n from 'i18next';
2import { initReactI18next } from 'react-i18next';
3
4
5import HttpApi from 'i18next-http-backend';
6
7
8import LanguageDetector from 'i18next-browser-languagedetector';
9
10i18n
11 .use(HttpApi)
12 .use(LanguageDetector)
13 .use(initReactI18next)
14 .init({
15 supportedLngs: ['en', 'fr', 'de'],
16 fallbackLng: 'en',
17 detection: {
18 order: ['queryString', 'cookie'],
19 caches: ['cookie']
20 },
21 backend: {
22
23 loadPath: '/locales/{{lng}}/translation.json'
24 }
25 });
26
27export default i18n;
3. 创建语言文件
在 public
目录下创建一个 locales
文件夹,然后为每种语言创建一个子文件夹,并在每个子文件夹中添加 translation.json
文件。例如:
1public
2└── locales
3 ├── en
4 │ └── translation.json
5 ├── fr
6 │ └── translation.json
7 └── de
8 └── translation.json
每个 translation.json
文件中包含翻译内容,例如:
1{
2 "welcome": "Welcome",
3 "description": "This is a description."
4}
4. 在 React 组件中使用
在你的应用根组件中引入 i18n
配置文件,并使用 I18nextProvider
包裹应用:
1import React from 'react';
2import ReactDOM from 'react-dom';
3import App from './App';
4import { I18nextProvider } from 'react-i18next';
5import i18n from './i18n';
6
7ReactDOM.render(
8 <I18nextProvider i18n={i18n}>
9 <App />
10 </I18nextProvider>,
11 document.getElementById('root')
12);
然后在组件中使用 useTranslation
钩子来获取翻译功能:
1import React from 'react';
2import { useTranslation } from 'react-i18next';
3
4function MyComponent() {
5 const { t } = useTranslation();
6
7 return (
8 <div>
9 <h1>{t('welcome')}</h1>
10 <p>{t('description')}</p>
11 </div>
12 );
13}
14
15export default MyComponent;
5. 切换语言
你可以通过调用 i18n.changeLanguage
方法来切换语言。例如,添加一个按钮来切换语言:
1import React from 'react';
2import { useTranslation } from 'react-i18next';
3
4function LanguageSwitcher() {
5 const { i18n } = useTranslation();
6
7 const changeLanguage = (lng) => {
8 i18n.changeLanguage(lng);
9 };
10
11 return (
12 <div>
13 <button onClick={() => changeLanguage('en')}>English</button>
14 <button onClick={() => changeLanguage('fr')}>Français</button>
15 <button onClick={() => changeLanguage('de')}>Deutsch</button>
16 </div>
17 );
18}
19
20export default LanguageSwitcher;
将这个 LanguageSwitcher
组件添加到你的应用中,你就可以通过点击按钮来切换语言了
这样,你的 React 应用就成功实现了国际化
个人笔记记录 2021 ~ 2025