React 國際化
前言
僅管市面上存在多款流行的國際化解決方案,但是筆者個人精力有限在此只記錄工作學習中遇到的解決方案(持續更新)
react-i18next 方案
1. 安裝
pnpm install react-i18next i18next --save
2. 創建文件
在 src 目錄下新建 locales ,並創建 en-US.json 、zh-CN.json 和 resources.js
en-US.json
{
"hello":"Hello"
}
zh-CN.json
{
"hello":"你好"
}
resources.js
import enUS from './en_US.json';
import zh from './zh_CN.json';
const resources = {
'en-US': {
translation: enUS,
},
'zh-CN': {
translation: zh,
},
zh: {
translation: zh,
},
};
export default resources;
在 src 下新建 i18n.ts
i18n.ts
import { initReactI18next } from 'react-i18next';
import i18n from 'i18next';
import resources from '@/locales/resources.js';
// the translations
// (tip move them in a JSON file and import them,
// or even better, manage them via a UI: https://react.i18next.com/guides/multiple-translation-files#manage-your-translations-with-a-management-gui)
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, // language to use, more information here: https://www.i18next.com/overview/configuration-options#languages-namespaces-resources
// you can use the i18n.changeLanguage function to change the language manually: https://www.i18next.com/overview/api#changelanguage
// if you're using a language detector, do not define the lng option
interpolation: {
escapeValue: false, // react already safes from xss
},
});
export default i18n;
3. 導入
在main.ts/index.ts中全局導入 i18n.ts
main.ts & index.ts
import './index.less';
import App from './App';
import React from 'react';
import ReactDOM from 'react-dom';
import './i18n' // 新增:導入i18n
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root'),
);
4. 使用
在要使用國際化的頁面使用useTranslation hook
Layout.tsx
import React from 'react';
// 頂部導入 useTranslation
import { useTranslation } from 'react-i18next';
const Layout: FC<any> = (props: PropsWithChildren<any>) => {
// 組件內部使用hook
const [t, i18n] = useTranslation();
// 在事件方法中使用i18n.changeLanguage()方法
const toggleI18n = () => {
const locale = i18n.language === "zh-CN" ? "en-US" : "zh-CN";
i18n.changeLanguage(locale)
}
return (
<div>
<button onClick={toggleI18n}> i18n切換 </button>
</div>
);
};
export default Layout;
5. 追加字典到現有語言項
如果依賴的第三方庫已經綁定過選項字典,可以通過如下方法添加自己的字典到現有的語言項中
創建字典的步驟和上述一致,但是在 main.ts 或者 index.ts 中的編寫方式有所不同
// main.ts & index.ts
import { resources } from "@/locales/resources"
import { useTranslation } from "react-i18next"
// 省略其他代碼...
const { i18n } = useTranslation();
Object.keys(resources).forEach((lan: string) => {
i18n.addResourceBundle(lang, 'translation', localResources[lang], true, false);
})