npm install i18next
yarn add i18next
import i18next from 'i18next';
i18next.init({
lng: 'en',
resources: {
en: {
translation: {
"welcome": "Welcome to our application"
}
},
fr: {
translation: {
"welcome": "Bienvenue dans notre application"
}
}
}
});
console.log(i18next.t('welcome')); // 输出: Welcome to our application
import React from 'react';
import ReactDOM from 'react-dom';
import { useTranslation, initReactI18next } from 'react-i18next';
import i18next from 'i18next';
i18next.use(initReactI18next).init({
lng: 'en',
resources: {
en: {
translation: {
"welcome": "Welcome to our application"
}
},
fr: {
translation: {
"welcome": "Bienvenue dans notre application"
}
}
}
});
function App() {
const { t } = useTranslation();
return <h1>{t('welcome')}</h1>;
}
ReactDOM.render(<App />, document.getElementById('root'));
options
:配置选项,包括语言、资源、后端等。callback
:初始化完成后的回调函数。key
:翻译字符串的键。options
:可选参数,如占位符、上下文等。lng
:新语言的代码。callback
:语言切换完成后的回调函数。namespaces
:命名空间列表。callback
:加载完成后的回调函数。lng
:语言代码。ns
:命名空间。resources
:资源对象。deep
:是否深度合并。overwrite
:是否覆盖现有资源。i18next 支持多种中间件,可以扩展功能,例如缓存、后端加载等。以下是使用 i18next-http-backend 的示例:
import i18next from 'i18next';
import HttpBackend from 'i18next-http-backend';
i18next.use(HttpBackend).init({
lng: 'en',
backend: {
loadPath: '/locales/{{lng}}/{{ns}}.json'
}
});
可以通过 i18next.format 选项自定义翻译结果的格式化。例如,自定义日期格式:
i18next.init({
lng: 'en',
resources: {
en: {
translation: {
"date": "Today's date is {{date, MM/DD/YYYY}}"
}
}
},
interpolation: {
format: function(value, format, lng) {
if (format === 'MM/DD/YYYY') {
return new Intl.DateTimeFormat('en-US').format(value);
}
return value;
}
}
});
console.log(i18next.t('date', { date: new Date() }));