i18next 是一个用 JavaScript 编写的国际化框架。
1、添加到你的项目:
npm install i18next react-i18next --save
或
yarn add i18next react-i18next
2、新建i18n文件夹,文件夹下新建i18n.js
import i18next from 'i18next';
import { initReactI18next } from 'react-i18next';
import en from '../common/lang/en-US/lang.json';
import zh from '../common/lang/zh-CN/lang.json';
const resources = {
zh_CN: {
lang: zh,
},
en_US: {
lang: en,
},
};
i18next
.use(initReactI18next)
.init({
resources,
load: 'currentOnly',
fallbackLng: 'zh_CN',
defaultNS: 'lang'
});
文案json 英文:
{
"welcome": "welcome",
"age": "age {{num}}"
}
文案json 中文:
{
"welcome": "欢迎",
"age": "年龄 {{num}}"
}
3、在你的应用程序的入口点引入i18n.js进行初始化
import '@src/i18n/i18n';
4、举个使用例子
import React from 'react';
import { useTranslation } from 'react-i18next';
function MyComponent(){
const { t, i18n } = useTranslation();
const age = 18;
// 切换语言
i18n.changeLanguage('en_US');
console.log('当前语言:', i18n.language);
return (
<>
<h2>{t('welcome')}</h2>
<h2>{t('age', { num: age })}</h2>
</>
);
}