如何使用React-Native和i18n-js获取当前语言环境?

时间:2019-10-07 08:19:42

标签: react-native

我是React-native的新手,我正在尝试从用户的设备获取当前语言环境。 目前,我有2个版本的应用程序:法语和英语。 当我更改后备语言时,它确实具有两个版本的应用,因此效果很好。 但是我无法直接从设备上更改语言...

我在许多页面中都使用了RNlocalize,但是它对我不起作用...我的App.js:

  import React, { Component } from "react";
import I18n from "./src/i18n/I18n";
import * as RNLocalize from "react-native-localize";

async handleLocales() {
  this.locales = RNLocalize.getLocales();
}

getLocale() {
  if (this.locales) {
    if (Array.isArray(this.locales)) {
      return this.locales[0];
    }
  }
  return null;
}
class App extends Component {
  render() {
    return (
      <View>
        <Text>{I18n.t("hello")}</Text>
      </View>
    );
  }
}
export default App;

我的i18n.js文件:

import I18n from "i18n-js";
import * as RNLocalize from "react-native-localize";

import en from "./locales/en";
import fr from "./locales/fr";

const locales = RNLocalize.getLocales();

if (Array.isArray(locales)) {
  I18n.locale = locales[0].languageTag;
}

I18n.fallbacks = true;
I18n.translations = {
  en,
  fr
};

export default I18n;

我在测试文件夹中尝试过。我遇到的错误是

SyntaxError: C:\Users\Administrateur\Desktop\App.js: Unexpected token, expected "=>" (5:19)

  3 | import * as RNLocalize from "react-native-localize";
  4 | 
> 5 | async handleLocales() {
    |                    ^
  6 |   this.locales = RNLocalize.getLocales();
  7 | }
  8 |

希望您能帮助我。而且,作为一个新手,我需要解释,因为它是新来的,而且我没有很多经验!

无论如何,感谢您的阅读。

2 个答案:

答案 0 :(得分:1)

尝试一下:

import { NativeModules, Platform } from 'react-native';

const locale =
  Platform.OS === 'ios'
    ? NativeModules.SettingsManager.settings.AppleLocale
    : NativeModules.I18nManager.localeIdentifier;

答案 1 :(得分:1)

我想我的语言环境有问题。 以这种方式纠正一切正常:

    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;
console.log(locale.substring(0, 2));
      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: false, // we do not use keys in form messages.welcome

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

export default i18n;

非常感谢!!!