简体   繁体   English

在React Native App中将语言更改为用户偏好

[英]Change Language as a user preferance in React Native App

I am creating an app using React Native and need the ability to change the app's language "on the fly" so to speak. 我正在使用React Native创建一个应用程序,并且需要能够“即时”更改应用程序的语言。 I have followed the sample here: https://github.com/appfoundry/react-native-multi-language-sample . 我在这里关注了示例: https : //github.com/appfoundry/react-native-multi-language-sample After following this I have successfully setup Redux and all of the accompanying libraries. 完成此操作后,我已经成功设置了Redux和所有附带的库。

The issue I'm having is that I'm trying to trigger my action from an alert popup not a picker and I'm having issues actually dispatching the action. 我遇到的问题是,我试图从警报弹出窗口而不是选择器中触发我的操作,而我在实际分派操作时遇到了问题。

If anyone can show me how to change the user language using an Alert that would be fantastic. 如果有人可以告诉我如何使用警报来更改用户语言,那将是很棒的。

Thanks! 谢谢!

I have worked on a situation that maybe the idea can help you. 我曾尝试过一种可能会帮助您的情况。

I used react-native-i18n ( https://github.com/AlexanderZaytsev/react-native-i18n ) and created a file with all my translations. 我使用react-native-i18nhttps://github.com/AlexanderZaytsev/react-native-i18n )并创建了一个包含所有翻译内容的文件。 Something like this: 像这样:

I18n.translations = {
  en: {
    helloWorld: 'Hello World!',
    loginButton: 'Login',
  }
}

Then I imported it in my component which contains the texts that should be translated and use it like this: 然后,将其导入到我的组件中,该组件包含应翻译的文本,并像这样使用它:

<View>
  <Text>{I18n.t('helloWorld'}</Text>
</View>

I have the user language stored in my database and I get it and set in my reducer when user logs in in my app. 我将用户语言存储在数据库中,并在用户登录我的应用程序时得到它并在我的reducer中进行设置。 At first I get the languge from I18n.currentLocale() method. 首先,我从I18n.currentLocale()方法获取语言。

In my component I get the user language from my reducer and set it on I18n config: I18n.locale = this.props.language; 在我的组件中,我从减速器获取用户语言,并将其设置为I18n config: I18n.locale = this.props.language;

In this component I have a picker so user can select its language. 在此组件中,我有一个选择器,因此用户可以选择其语言。 I trigger an action to update my database, as well the reducer and use componentWillReceiveProps() lifecycle to update I18n.locale value 我触发一个操作来更新我的数据库以及reducer,并使用componentWillReceiveProps()生命周期来更新I18n.locale

componentWillReceiveProps(nextProps) {
    I18n.locale = nextProps.language;
  }

Hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM