useTranslation
钩子和 Trans
组件,简化翻译文本的使用和模板化。npm install react-i18next i18next
yarn add react-i18next i18next
import React from 'react';
import ReactDOM from 'react-dom';
import { I18nextProvider } from 'react-i18next';
import i18next from 'i18next';
import App from './App';
i18next.init({
lng: 'en',
resources: {
en: {
translation: {
"welcome": "Welcome to our application"
}
},
fr: {
translation: {
"welcome": "Bienvenue dans notre application"
}
}
}
});
ReactDOM.render(
<I18nextProvider i18n={i18next}>
<App />
</I18nextProvider>,
document.getElementById('root')
);
useTranslation
钩子import React from 'react';
import { useTranslation } from 'react-i18next';
function MyComponent() {
const { t } = useTranslation();
return <h1>{t('welcome')}</h1>;
}
export default MyComponent;
Trans
组件import React from 'react';
import { Trans } from 'react-i18next';
function MyComponent() {
return (
<Trans i18nKey="description.part1">
To get started, edit <code>src/App.js</code> and save to reload.
</Trans>
);
}
export default MyComponent;
t
和当前语言 i18n
实例。
const { t, i18n } = useTranslation();
t('key')
用于获取翻译字符串。<Trans i18nKey="key">Your text</Trans>
export default withTranslation()(MyComponent);
<I18nextProvider i18n={i18next}>...</I18nextProvider>
i18next.use(initReactI18next).init({...})
可以通过配置自定义的语言检测逻辑,例如从 URL、cookie 或浏览器设置中检测语言:
import LanguageDetector from 'i18next-browser-languagedetector';
i18next
.use(LanguageDetector)
.use(initReactI18next)
.init({
detection: {
order: ['querystring', 'cookie', 'localStorage', 'navigator', 'htmlTag', 'path', 'subdomain'],
caches: ['localStorage', 'cookie']
},
// 其他配置
});
使用 i18next-http-backend
插件动态加载翻译文件,减小初始包大小:
import Backend from 'i18next-http-backend';
i18next
.use(Backend)
.use(initReactI18next)
.init({
backend: {
loadPath: '/locales/{{lng}}/{{ns}}.json'
},
// 其他配置
});
想了解更多可以参考官方资料