Change Language as a user preferance in React Native App

给你一囗甜甜゛ 提交于 2021-01-28 08:11:47

问题


I am creating an app using React Native and need the ability to change the app's language "on the fly" so to speak. I have followed the sample here: https://github.com/appfoundry/react-native-multi-language-sample. After following this I have successfully setup Redux and all of the accompanying libraries.

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!


回答1:


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. 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. At first I get the languge from I18n.currentLocale() method.

In my component I get the user language from my reducer and set it on 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

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

Hope it helps



来源:https://stackoverflow.com/questions/46493150/change-language-as-a-user-preferance-in-react-native-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!