我希望我的应用程序包含一个设置屏幕,以便我可以从选择器更改语言。我希望语言更改反映在整个应用程序上,并且我希望应用程序记住最后选择的语言。下面给出了我的 index.js,它为 en、am 或 tg 导入了我的键值对语言,
index.js
import * as RNLocalize from 'react-native-localize';
import I18n from 'i18n-js';
import memoize from 'lodash.memoize';
import en from './en';
import am from './am';
import or from './or';
import tg from './tg';
const locales = RNLocalize.getLocales();
if (Array.isArray(locales)) {
I18n.locale = locales[0].languageTag;
}
I18n.translations = {
default: en,
'en-US': en,
en,
am,
or,
tg,
};
I18n.fallbacks = true;
export default I18n;
我想从我的设置屏幕更改应用程序的语言。我准备了一个选择器来选择语言。下面给出了我的设置屏幕代码。
设置屏幕.js
import I18n from './../i18n/locales';
const width = Dimensions.get('window').width;
const height = Dimensions.get('window').height;
const listLanguage = [
{key:'en', label:'En'}, {key:'am', label:'Am'} ,{key:'or', label: 'OR'}, {key:'tg', label:'TG'},]
export default class SettingsScreen extends React.Component {
constructor(props) {
super(props);
this.state = { visible: true ,
languageSelected: 'en'
};
}
backToMain() {
this.props.navigation.navigate('LocationTrackingScreen', {});
}
handleBackPress = () => {
this.props.navigation.navigate('LocationTrackingScreen', {});
return true;
};
hideSpinner() {
this.setState({ visible: false });
}
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
}
onChangeLanguage(languageSelected){
this.setState({
languageSelected
})
I18n.locale = languageSelected
}
render() {
const {languageSelected} = this.state
return (
<SafeAreaView style={styles.container}>
<View style={styles.containerDropdown}>
<DropdownLanguage language={languageSelected} onChangeLanguage={this.onChangeLanguage.bind(this)}></DropdownLanguage>
</View>
</SafeAreaView>
);
}
}
class DropdownLanguage extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<View style={styles.dropdown}>
<Picker
mode="dropdown"
iosHeader={''}
style={{ width: width,height:70,}}
selectedValue={this.props.language}
onValueChange={this.props.onChangeLanguage.bind(this)}
>
{listLanguage.map((languageItem, i) => {
return <Picker.Item key={i} value={languageItem.key} label= {languageItem.label} />
})}
</Picker>
</View>
)
}
}