1

我希望我的应用程序包含一个设置屏幕,以便我可以从选择器更改语言。我希望语言更改反映在整个应用程序上,并且我希望应用程序记住最后选择的语言。下面给出了我的 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>
)
  }
}
4

2 回答 2

2

您可以将所选语言保存在 AsyncStorage 中,当用户打开应用程序时,您可以从 AsyncStorage 中检查最后选择的语言并将其设置为应用程序语言。这是我在项目中如何做的一个例子:

在语言更改时,像这样在 AsyncStorage 中设置语言

    export const changeLanguage = async lang => {
         setI18nConfig(lang);
         AsyncStorage.setItem('language', lang);
     };

当用户重新打开应用程序时,只需在第一个屏幕上获取语言并将其设置为应用程序语言,如下所示

let language = await AsyncStorage.getItem('language');
changeLanguage(language);

我希望这能帮到您

于 2020-05-08T15:34:52.217 回答
0

只需创建一个名为 TranslationManager.js 的文件并在其中粘贴以下代码

import * as RNLocalize from 'react-native-localize';
import i18n from 'i18n-js';
import memoize from 'lodash.memoize';
import {I18nManager, AsyncStorage} from 'react-native';

const translationGetters = {
  // lazy requires (metro bundler does not support symlinks)
  en: () => require('./Languages/en.json'),
  ar: () => require('./Languages/ar.json'),
};
export const translate = memoize((key, config) => i18n.t(key, config));
// export const translate = text => {
//   console.log(i18n.t(text));
// };

export const setI18nConfig = lang => {
  // fallback if no available language fits
  const fallback = {languageTag: 'en', isRTL: false};

  const {isRTL, languageTag} =
    RNLocalize.findBestAvailableLanguage(Object.keys(translationGetters)) ||
    fallback;

  // clear translation cache
  translate.cache.clear();
  // update layout directio
  // set i18n-js config
  I18nManager.forceRTL(false);
  i18n.translations = {['en']: translationGetters.en()};
  i18n.locale = 'en';

  if (lang) {
    i18n.translations = {[lang]: translationGetters[lang]()};
    i18n.locale = lang;
  } else {
    i18n.translations = {['en']: translationGetters.en()};
    i18n.locale = 'en';
  }
};

export const changeLanguage = async lang => {
  setI18nConfig(lang);
  AsyncStorage.setItem('language', lang);
};

export const isRTL = () => {
  return translate('lang') === 'ar' ? true : false;
};

不,您有一个单独的类来更改应用程序的语言。只需在任何你想要的地方导入这个 changeLanguage 函数,然后像这样更改语言:

import {changeLanguage} from '../../Translations/TranslationManager';
let language = await AsyncStorage.getItem('language');
changeLanguage(language);

您可以通过这种方式显示您的翻译文本:

import {translate} from '../../Translations/TranslationManager';
<Text>translate('ForumScreen.title')</Text>

希望它现在和将来对您有所帮助。

于 2020-05-08T16:28:24.147 回答