react-i18next实现网站国际化

由于时效问题,该文某些代码、技术可能已经过期,请注意!!!本文最后更新于:9 个月前

如题

经过网络上简单调研最终选择了react-i18next来实现中英切换。安装就不说了,实现的脚本都放到assests文件夹里了。

1
2
3
4
5
6
7
assets
├── i18n.js
├── locales
│ ├── cn.json
│ ├── en.json
│ └── resources.js
└── useCustomTranslation.js

i18n.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { initReactI18next } from 'react-i18next';
import i18n from 'i18next';
import resources from './locales/resources.js';

let localLang = sessionStorage.getItem('lang');
const browserLang = navigator.language;

if (!localLang) {
localLang = browserLang === 'zh-CN' ? 'zh-CN' : 'en-US';
}

i18n
.use(initReactI18next) // passes i18n down to react-i18next
.init({
resources,
lng: localLang,
interpolation: {
escapeValue: false, // react already safes from xss
},
});

export default i18n;

useCustomTranslation.js

1
2
3
4
5
6
7
8
9
10
11
12
import { useTranslation } from 'react-i18next';

export function useCustomTranslation() {
const [t, i18n] = useTranslation();

const toggleI18n = () => {
const locale = i18n.language === "zh-CN" ? "en-US" : "zh-CN";
i18n.changeLanguage(locale);
};

return { t, toggleI18n };
}

resources.js

1
2
3
4
5
6
7
8
9
10
11
12
13
import en from './en.json';
import cn from './cn.json';

const resources = {
'en-US': {
translation: en,
},
'zh-CN': {
translation: cn,
}
};

export default resources;

cn.json、en.json

参考格式

1
2
3
4
5
6
7
8
// locales/en-US.json
{
"hello":"Hello"
}
// locales/zh-CN.json
{
"hello":"你好"
}

如何使用

1、在index.js中全局导入i18n.js

1
import './assets/i18n';

2、在需要转换的页面导入useCustomTranslation.js

1
2
3
4
5
6
7
8
9
10
11
12
13
import { useCustomTranslation } from './assets/useCustomTranslation';

## 在组件中定义
const Welcome = () => {
const { t, toggleI18n } = useCustomTranslation();
return (
<div>
国际化测试数据: {t('hello')}
</div>
);
};
export default Welcome;

完整代码:https://github.com/shubihu/letsthink.git

参考:https://blog.csdn.net/muou_hang/article/details/119647094


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!