i18n优化
This commit is contained in:
parent
717730eed7
commit
62c5c2a82a
73
src/translate/I18Next.tsx
Normal file
73
src/translate/I18Next.tsx
Normal file
@ -0,0 +1,73 @@
|
|||||||
|
import i18n from 'i18next';
|
||||||
|
import { initReactI18next } from 'react-i18next';
|
||||||
|
import Backend from 'i18next-http-backend'; // 引入 Backend 插件
|
||||||
|
import { useEffect, useLayoutEffect, useState } from 'react';
|
||||||
|
|
||||||
|
type I18NextProviderProps = {
|
||||||
|
children: React.ReactNode;
|
||||||
|
basename?: string;
|
||||||
|
noUse?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const initI18n = async (basename: string) => {
|
||||||
|
// 初始化 i18n
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
i18n
|
||||||
|
.use(Backend) // 使用 Backend 插件
|
||||||
|
.use(initReactI18next)
|
||||||
|
.init(
|
||||||
|
{
|
||||||
|
backend: {
|
||||||
|
loadPath: `${basename}/locales/{{lng}}/{{ns}}.json`, // 指定 JSON 文件的路径
|
||||||
|
},
|
||||||
|
lng: 'zh', // 默认语言
|
||||||
|
fallbackLng: 'en', // 备用语言
|
||||||
|
interpolation: {
|
||||||
|
escapeValue: false, // react 已经安全地处理了转义
|
||||||
|
},
|
||||||
|
},
|
||||||
|
(e) => {
|
||||||
|
console.log('e', e);
|
||||||
|
resolve(true);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 国际化组件,初始化
|
||||||
|
* @param props
|
||||||
|
* @returns
|
||||||
|
*/
|
||||||
|
export const I18NextProvider = (props: I18NextProviderProps) => {
|
||||||
|
const { children, basename, noUse } = props;
|
||||||
|
if (noUse) {
|
||||||
|
return <>{children}</>;
|
||||||
|
}
|
||||||
|
const [init, setInit] = useState(false);
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
initCheck();
|
||||||
|
}, []);
|
||||||
|
const initCheck = async () => {
|
||||||
|
let _currentBasename = '';
|
||||||
|
if (typeof basename === 'undefined') {
|
||||||
|
const local = localStorage.getItem('locale-basename');
|
||||||
|
if (local) {
|
||||||
|
_currentBasename = local;
|
||||||
|
} else {
|
||||||
|
_currentBasename = '';
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
_currentBasename = basename;
|
||||||
|
}
|
||||||
|
if (_currentBasename === '/') {
|
||||||
|
_currentBasename = '';
|
||||||
|
}
|
||||||
|
initI18n(_currentBasename);
|
||||||
|
setInit(true);
|
||||||
|
};
|
||||||
|
if (!init) {
|
||||||
|
return <></>;
|
||||||
|
}
|
||||||
|
return <>{children}</>;
|
||||||
|
};
|
4
src/translate/index.tsx
Normal file
4
src/translate/index.tsx
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
export * from './I18Next.tsx';
|
||||||
|
|
||||||
|
export { useTranslation };
|
Loading…
x
Reference in New Issue
Block a user