(this article is also available on RNTricks: https://www.rntricks.com/article/7-easy-steps-to-localize-your-react-native-app)
(本文也可以在RNTricks上找到: https ://www.rntricks.com/article/7-easy-steps-to-localize-your-react-native-app )
您应该选择哪个图书馆? (Which Library Should You Choose?)
It is true that any translation library that works for React will also do the trick for React Native. There are about 5 or 6 main options that you could choose from, but after counting up the pros and cons of each one, we decided to go with i18next.
这是事实,任何翻译库,为作品做出React也会做阵营本土的伎俩。 您可以从大约5或6个主要选项中进行选择 ,但是在计算出每个选项的利弊之后,我们决定选择i18next 。
i18next is a free library that offers a quick “getting started” routine, as well as some nice plug-n-play features that you might find useful and opt for later.
i18next是一个免费库,提供了快速的“入门”例程以及一些不错的即插即用功能,您可能会发现它们有用并在以后选择。
Let’s get started!
让我们开始吧!
1.安装i18next (1. Install i18next)
npm install i18next --save
npm install i18next --save
2.为英语创建空的翻译文件 (2. Create empty translation file for English)
Create a file and put it in a folder that works best for you (e.g. /translations/en.tsx
), where you will later add translation files for all your supported languages. It should, for now, look something like this:
创建一个文件并将其放在最适合您的文件夹中(例如/translations/en.tsx
),稍后您将在其中添加所有受支持语言的翻译文件。 现在,它应该看起来像这样:
const translation = {};
export default translation;
3.初始化库并为其提供刚创建的文件 (3. Initialize the library and supply it with the file you just created)
Add this code somewhere at the top of your root component:
将此代码添加到根组件顶部的某个位置:
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import en from './translation/en'; i18n
.use(initReactI18next)
.init({
lng: 'en',
fallbackLng: 'en',
debug: true,
interpolation: {
escapeValue: false,
},
resources: {
en: {
translation: en,
},
},
});
The initialization is pretty straightforward, but can take in quite a few configuration options based on your needs. You can see all of them here.
初始化非常简单,但是可以根据您的需要采用许多配置选项。 您可以在这里看到所有这些。
But right now, we can already go ahead and try it out:
但是现在,我们已经可以继续尝试:
import i18next from 'i18next';
render() {
return (
<Text>{i18next.t('Hello world!')}</Text>
)
}
4.使“ T'
功能全局可用 (4. Make the 'T’
function available globally)
This will save a lot of time during development, as it removes the need to prefix the t
function with i18next.
every time.
这将节省开发过程中的大量时间,因为它无需在t
函数前加上i18next.
前缀i18next.
每次。
Add this in your root component:
将此添加到您的根组件中:
import i18next from 'i18next';global.T = i18next.t;
Now, instead of importing 18next
every time, we can just call T
:
现在,我们18next
每次都导入18next
,而只需调用T
:
render() {
return (
<Text>{T('Hello world!')}</Text>
)
}
Shorter, cleaner and quicker to write.
写得更短,更干净,更快捷。
Feel free to use t
instead of T
. We prefer it for visibility.
随意使用 t
,而不是 T
。 我们更喜欢它的可见性。
5.为您的“ T'
电话添加强类型 (5. Add strong typing to your ‘T’
calls)
This is not mandatory, but with some TS magic and very little code, we can achieve static checking for our keys when calling T
. Modify your previous code as follows:
这不是强制性的,但是使用一些TS魔术和很少的代码,我们可以在调用T
时实现对密钥的静态检查。 修改您以前的代码,如下所示:
import i18next from 'i18next';import translation from './translation/en';type TKeys = keyof typeof translation;function translate<K extends TKeys>(key: K, options?: Object) {
return i18next.t(key, options);
}global.T = translate;
We are importing the already existing translation file that has all our english keys, and using them to statically analyze and validate our T calls. Sweet!
我们将导入包含所有英语键的现有翻译文件,并使用它们静态分析和验证T调用。 甜!
Now, whenever we attempt to translate using a non-existing key, we get a static compiler warning:
现在,每当我们尝试使用不存在的键进行翻译时,都会收到静态编译器警告:
![Image for post](https://miro.medium.com/max/9999/0*_Bx0mOMnNHVzkQcI.jpg)
6.不要将每个键手动添加到我们的字典中 (6. Not adding every single key by hand to our dictionary)
So, after we’ve wrapped our labels like T('Some key')
, we need to somehow get our key ('Some key'
) into the translation file.
因此,在将标签包装成T('Some key')
,我们需要以某种方式将我们的密钥( 'Some key'
)放入翻译文件中。
This could be done manually, but, depending on the size of your project, it might be really time-consuming and will definitely not feel like a coder’s job.
这可以手动完成,但是根据项目的大小,这可能确实很耗时,而且绝对不会像编码员那样工作。
Here’s where one of i18next’s many features comes into play. The tool that we will be using is called locize (read more about it and/or register for it here).
这就是i18next众多功能之一发挥作用的地方。 我们将使用的工具称为locize ( 在此处了解更多信息和/或注册)。
What it’s gonna do for us: whenever we call i18next.t
with a certain key, the library will automatically check if the key already exists, and if not, add it to the dictionary that we can then easily export and put into our project. Nice!
它会为我们做什么:每当我们使用某个键调用i18next.t
时,库都会自动检查该键是否已经存在,如果不存在,请将其添加到字典中,然后我们可以轻松地将其导出并放入我们的项目中。 真好!
Add the following to your init:
将以下内容添加到您的init中:
import i18n from 'i18next';
//install this before importingimport Backend from 'i18next-locize-backend';
import { initReactI18next } from 'react-i18next';
import en from './translation/en'; const locizeOptions = {
projectId: 'take it from locize',
apiKey: 'same',
referenceLng: 'en',
}; i18n
.use(initReactI18next)
.use(Backend)
.init({
lng: 'en',
fallbackLng: 'en',
debug: true,
interpolation: {
escapeValue: false,
},saveMissing: true,
resources: {
en: {
translation: en,
},
},
});
Now if you navigate to a screen that uses the T
function, your key will automatically be added to locize:
现在,如果您导航到使用T
功能的屏幕,您的按键将自动添加到locize :
![Image for post](https://miro.medium.com/max/9999/0*4RxEqUkOKb_ZVvYK.jpg)
Now whenever you feel like it, export the dictionary to a JSON
using the "...More" context menu in the top right. The file will look like this:
现在,只要您愿意,就可以使用右上方的“ ... More”上下文菜单将字典导出为JSON
。 该文件将如下所示:
{
'Be the first to start a discussion!': 'Be the first to start a discussion!',
'Drum roll for the': 'Drum roll for the',
'Other key': 'Other key'
}
7.改变语言 (7. Changing the language)
![Image for post](https://miro.medium.com/max/9999/0*vyDWwLIpwqdFzCzn.png)
Changing the language is simply telling i18next to “use another resource file” (e.g. fr.tsx). To do this, we need to wrap the component from which we want to change the language with the withTranslation
HOC:
更改语言只是告诉i18next “使用另一个资源文件”(例如fr.tsx)。 为此,我们需要使用withTranslation
HOC包装要更改其语言的withTranslation
:
export default withTranslation()(RootComponent)
And then it’s as simple as calling
然后就像调用一样简单
this.props.i18n.changeLanguage(languageCode);
inside your component.
在组件内部。
Here, languageCode
is one of the provided keys inside ofresources
in the i18next initialization object.
在这里, languageCode
是i18next初始化对象中resources
内部提供的键之一。
8.我们完成了! (8. And We’re Done!)
There are still some nice things you could do, such as putting your T
inside of a custom Text
component that you would use instead of the default one, to get you writing even less T
s, but other than that, these steps will get you to a point in which you can get to a fully translation-ready app in as little as a day. And then it's just a matter of sending the files to the translators!
您仍然可以做一些不错的事情,例如将T
放入自定义Text
组件中,而不是使用默认的Text
组件,以使您编写的T
更少,但是除此之外,这些步骤还可以帮助您到了一天之内就可以使用完全翻译就绪的应用程序的地步。 然后,只需将文件发送给翻译人员即可!
翻译自: https://medium.com/swlh/7-easy-steps-to-localize-your-react-native-app-6622658d1624