更改整个本机应用程序的语言

问题描述 投票:0回答:1

我在react-native中的应用程序有2种语言:英语和法语。我已经完成了一个i18n.js文件和2个针对英语和法语的“ translation.js”文件。效果很好(我尝试过在手机上设置法语,在模拟器上设置英语)。

现在,我想在应用程序设置中创建一个按钮,以为用户更改整个应用程序的语言,但是我不知道调用什么函数以及如何创建该函数。

您能帮我吗?非常感谢您的时间和帮助。

我的i18n.js文件;

import i18n from "i18next";
import detector from "i18next-browser-languagedetector";
import { reactI18nextModule } from "react-i18next";
import { NativeModules, Platform } from "react-native";

import en from "../public/locales/en/translation.js";
import fr from "../public/locales/fr/translation.js";

// the translations
const resources = {
  en: {
    translation: en
  },
  fr: {
    translation: fr
  }
};
const locale =
  Platform.OS === "ios"
    ? NativeModules.SettingsManager.settings.AppleLocale
    : NativeModules.I18nManager.localeIdentifier;

i18n.locale = locale;

i18n
  .use(detector)
  .use(reactI18nextModule) // passes i18n down to react-i18next
  .init({
    resources,
    lng: locale.substring(0, 2),
    fallbackLng: "en", // use en if detected lng is not available

    keySeparator: ".", // we do not use keys in form messages.welcome

    interpolation: {
      escapeValue: false // react already safes from xss
    }
  });

export default i18n;

而且我想从我的Settings.js文件中更改语言:

<SettingsList.Item
              // icon={<Image style={styles.image} source={require('../../assets/images/icon_vol-mute.png')}/>}
              title={i18n.t("settings.action.languages")}
              hasNavArrow={false}
              switchState={this.state.activeSwitch === 3}
              switchOnValueChange={this.switchThree}
              hasSwitch={true}
              onPress={() => Alert.alert("French / English")}
            />
function react-native translate i18next
1个回答
0
投票

在通常情况下。有两种方法可以实现您的目的。

使用react-native-i18nreact-native-localization

但是我建议react-native-localizationsimply in implementation推荐native performance

如何使用react-native-localization

安装

yarn add react-native-localization --save

#react-native >= 0.60
cd ios && pod install && cd ..

#react-native < 0.60
react-native link react-native-localization

翻译您的翻译

import LocalizedStrings from 'react-native-localization';
import english from './en.js'
import french from './fr.js'
import korean from './kr.js'

const strings = new LocalizedStrings({
 en: english,
 fr: french,
 kr: korean,
});

带有en.jsfr.jskr.js的文件包含您以key value格式进行的翻译。

例如:fr.js的内容

export default {
ok: 'D'accord',
no: 'non'
}

您也可以使用json文件类型进行声明。

用法

import strings from 'services/translation';

<Text style={styles.title}>
  {strings.ok}
</Text>

更改语言

编写一个功能来更改您的应用语言,并在您需要的任何地方使用它。

const strings = new LocalizedStrings({
 en: english,
 fr: french,
 kr: korean,
});


export const changeLaguage = (languageKey) => {
strings.setLanguage(languageKey)
}
import { changeLaguage } from 'services/translation'


<Button onPress={() => {changeLanguage(languageKey)}} />

注意:不要在默认方法,例如setLanguage中声明相同的键

查看有关react-native-localization here的更多信息
© www.soinside.com 2019 - 2024. All rights reserved.