react i18n配置
时间: 2023-08-18 11:05:14 浏览: 58
React i18n 是一个用于 React 应用的国际化工具,可以帮助我们方便地实现多语言支持。下面是 React i18n 的配置步骤:
1. 安装 i18next 和 react-i18next
```
npm install i18next react-i18next
```
2. 创建语言文件
在项目中创建一个 `public/locales` 目录,用来存放不同语言的翻译文件。例如:在 `public/locales` 目录下创建一个 `en/translation.json` 文件,用来存放英文的翻译内容。文件内容如下:
```
{
"hello": "Hello World!"
}
```
3. 初始化 i18next
在项目入口文件中初始化 i18next,例如在 `src/index.js` 文件中添加以下代码:
```
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
i18n.use(initReactI18next).init({
resources: {
en: {
translation: require('./locales/en/translation.json')
}
},
lng: 'en',
fallbackLng: 'en',
interpolation: {
escapeValue: false
}
});
```
4. 使用 i18n
在需要使用翻译内容的地方,可以使用 `useTranslation` hook 来获取翻译函数。例如:
```
import React from 'react';
import { useTranslation } from 'react-i18next';
function MyComponent() {
const { t } = useTranslation();
return <h1>{t('hello')}</h1>;
}
```
上面的代码中,`t` 是一个函数,用于获取翻译内容,`'hello'` 是需要翻译的内容的键值。
以上就是 React i18n 的配置步骤。