问题
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