更改整个React Native App的语言 [英] Change language of entire React Native App

查看:64
本文介绍了更改整个React Native App的语言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个React Native应用程序,其中的默认语言是英语.我有一个个人资料页面,用户可以在其中将语言从英语更改为另一种语言.当用户保存语言更改时,包括标题,抽屉导航名称在内的所有语言都应更改为用户选择的语言.我们如何在React Native中实现此功能?

I have a react native application in which the default language is English. I have a profile page in which the user can change the language from English to another language. And when the user saves the language change, the language including the title, drawer navigation names all should be changed to the user chosen language. How we can implement this functionality in react native?

推荐答案

您可以使用此软件包: https://github.com/AlexanderZaytsev/react-native-i18n

You can use this package: https://github.com/AlexanderZaytsev/react-native-i18n

安装后,您要做的就是定义区域设置文件,例如:

Once installed all you have to do is to define your locale files, for example:

// src/i18n/locales/en.js
export default {  
  greeting: 'Hi!'
};

// src/i18n/locales/es.js
export default {  
  greeting: 'Hola!'
};

// src/i18n/locales/jp.js
export default {  
  greeting: 'Konichiwa!'
};

然后导入这些文件并按如下所示设置i18n支持的配置:

Then import those files and setup the configuration for i18n support like this:

// src/i18n/index.js
import I18n from 'react-native-i18n';
import en from './locales/en';
import es from './locales/es'; 
import jp from './locales/jp';  

I18n.fallbacks = true;

I18n.translations = {
  en,
  es,
  jp,
};

export default I18n; 

最后像这样在您的组件中使用它:

And finally use it in your components like this:

import I18n from 'src/i18n';

class Demo extends React.Component {
  render () {
    return (
      <Text>{I18n.t('greeting')}</Text>
    )
  }
}

默认情况下,它将使用设备的语言环境,但是如果您要覆盖该语言环境.例如,当用户使用具有西班牙语语言环境的设备但想要使用日语时,您可以执行以下操作:

By default it will use the device's locale, but if you want to overwrite that. For example when the user has device with a Spanish locale, but want to use Japanese, you can do something like this:

I18n.locale = 'jp';

无论何时调用 I18n.t('greeting'),它都会呈现 Konichiwa!.从现在开始,您将始终需要使用 I18n.t 来呈现应用程序中的任何文本.

Whenever you call I18n.t('greeting') it will render Konichiwa!. From now on, you will always need to use I18n.t to render any text in your app.

该库的主要问题是,一旦应用增长,您就不知道哪些键仍在使用中,管理所有翻译非常困难,我建议您使用像LinguiJS这样的工具: https://bleext.com/post/translating-your-product多种语言

The main issue with this library is the fact that you don't know which keys are still in use once your app grows, managing all your translations is super challenging, I'd recommend you to use a tool like LinguiJS for that: https://bleext.com/post/translating-your-product-into-multiple-languages

这篇关于更改整个React Native App的语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆