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

Kim*_*ako 2 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;
Run Code Online (Sandbox Code Playgroud)

我的 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;
Run Code Online (Sandbox Code Playgroud)

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

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 |
Run Code Online (Sandbox Code Playgroud)

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

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

Hen*_*hli 6

尝试这个:

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

const locale =
  Platform.OS === 'ios'
    ? NativeModules.SettingsManager.settings.AppleLocale
    : NativeModules.I18nManager.localeIdentifier;
Run Code Online (Sandbox Code Playgroud)