如何使用 i18next 翻译你的 React.js 应用
今天,我将向您展示如何在 React.js 应用程序中翻译文本和日期。
首先,您必须安装一些依赖项:
yarn add i18next i18next-xhr-backend i18next-browser-languagedetector react-i18next
现在我们需要在src文件夹中创建一个名为i18n.js的文件:
import i18n from 'i18next';
import Backend from 'i18next-xhr-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
import { initReactI18next } from 'react-i18next';
const fallbackLng = ['en'];
const availableLanguages = ['en', 'ru'];
i18n
.use(Backend) // load translation using xhr -> see /public/locales. We will add locales in the next step
.use(LanguageDetector) // detect user language
.use(initReactI18next) // pass the i18n instance to react-i18next.
.init({
fallbackLng, // if user computer language is not on the list of available languages, than we will be using the fallback language specified earlier
debug: true,
whitelist: availableLanguages,
interpolation: {
escapeValue: false
},
});
export default i18n;
然后我们将在src/index.js中的index.js中导入 i18n :
...
import './i18n';
ReactDOM.render(<App />, document.getElementById('root'));
...
下一步是创建我们的语言环境:public/locales/en/translation.json和public/locales/ru/translation.json。借助 i18next-xhr-backend,翻译将自动加载。
另外,在我们的App.js中,我们需要添加 Suspense 以显示加载指示器。
import React, { Suspense } from 'react';
...
function App() {
return (
<div className="App">
<Suspense fallback={(<div>Loading</div>)}>
<WeatherForecast />
</Suspense>
</div>
);
}
...
现在我们转到要翻译的组件。如果你有一个类组件,我们将使用高阶组件withTranslation:
import React, { Component } from 'react';
import { withTranslation } from 'react-i18next';
class News extends Component {
render(){
const { t } = this.props;
return (
<h1>{t('news.title')}</h1>
)
};
};
export default withTranslation()(News);
如果你有一个函数组件,你应该使用 react hook useTranslation:
import React from 'react';
import { useTranslation } from 'react-i18next';
const WeatherForecast = () => {
const { t } = useTranslation();
return (
<h1>{t('weather.title')}</h1>
)
};
export default WeatherForecast;
现在我们将修改我们的语言环境。在public/locales/en/translation.json中:
{
"news": {
"title": "Our news"
},
"weather": {
"title": "Weather forecast"
}
}
在public/locales/ru/translation.json 中:
{
"news": {
"title": "Наши новости"
},
"weather": {
"title": "Прогноз погоды"
}
}
如果您想翻译一个带有变量的短语,您需要这样做:
<p>{t('weather.temprature', {number: temprature})}</p>
在您的 .json 语言环境中,您需要写入:
"temprature": "Today in Lyon is cloudy: {{number}}°C."
我们将对俄语或任何其他版本采取同样的措施。
现在我将向你展示如何翻译日期。我将使用 moment.js 来实现。
yarn add moment
在我的WeatherForecast.js中我添加:
<p>{t('weather.date', {date: Date.now()})}</p>
现在在public/locales/en/translation.json 中:
"weather": {
"date": "Today's date: {{date, currentDate}}"
},
这里的{{}}
date是值,是我们在组件中分配的变量,currentDate是我们接下来将使用的格式。
在我们的 i18n.js 文件中,我们必须导入 moment.js 并配置日期的翻译:
import moment from 'moment';
...
availableLanguages.forEach((element) => {
if (element !== 'en') {
import(`moment/locale/${element}`);
}
}); // we are importing only the locales that we need.
.init({
...
interpolation: {
escapeValue: false,
format: (value, format, lng) => {
if (format === 'currentDate') return
moment(value).locale(lng).format('LL');
return value;
},//if the format is 'currentDate', then take its __value__ transfom it to a moment object, translate it to the current language and show it in Month DD, YYYY format.
},
});
应该可以正常工作。希望本文对您有所帮助。
鏂囩珷鏉ユ簮锛�https://dev.to/ksushiva/how-to-translate-your-react-js-app-with-i18next-12mn