eva*_*van 36

不需要外部库.您可以在React的Native Modules中找到

import { NativeModules } from 'react-native'

// iOS:
const locale = NativeModules.SettingsManager.settings.AppleLocale // "fr_FR"

// Android:
const locale = NativeModules.I18nManager.localeIdentifier // "fr_FR"
Run Code Online (Sandbox Code Playgroud)

为了测试这一点,我将设备上的语言更改为法语.以下是NativeModules.SettingsManager.settings与区域设置相关的对象中的示例:

{
    ...
    AppleKeyboards: [
        "fr_FR@hw=US;sw=QWERTY",
        "en_US@sw=QWERTY;hw=Automatic",
        "es_419@sw=QWERTY-Spanish;hw=Automatic",
        "emoji@sw=Emoji"
    ]
    AppleLanguages: ["fr-US", "en-US", "es-US", "en"]
    AppleLanguagesDidMigrate: "9.2"
    AppleLocale: "fr_FR"
    NSLanguages: ["fr-US", "en-US", "es-US", "en"]
    ...
}
Run Code Online (Sandbox Code Playgroud)

  • 使用Android的"NativeModules.I18nManager.localeIdentifier" (8认同)
  • 当使用iOS13 SDK构建的本机应用程序时,这似乎在iOS13上中断。 (3认同)
  • @TomSwift 看来这只是模拟器上的情况。它在我的 iOS 13 设备上运行良好。 (3认同)

Fir*_*med 20

下面的函数将返回一个2个字母的语言代码.例如:en

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

const deviceLanguage =
      Platform.OS === 'ios'
        ? NativeModules.SettingsManager.settings.AppleLocale ||
          NativeModules.SettingsManager.settings.AppleLanguages[0] //iOS 13
        : NativeModules.I18nManager.localeIdentifier;

console.log(deviceLanguage); //en_US
Run Code Online (Sandbox Code Playgroud)

  • 从iOS 13开始,不再显示AppleLocale。有人有针对iOS 13的解决方法吗? (3认同)
  • 从 ios 14 开始,“AppleLocale”和“AppleLanguages”似乎都已定义。建议现在首先选择“AppleLanguages”,因为它支持应用程序特定的首选语言功能。并使用可选链接以更好地实现向后兼容性 (3认同)

eya*_*l83 13

我正在使用i18n软件包(react-native-i18n).然后就是:

I18n = require('react-native-i18n')
locale = I18n.currentLocale()
Run Code Online (Sandbox Code Playgroud)

  • 在新版本的React FYI人中出现错误。 (2认同)
  • 该软件包已被弃用。您可以使用“react-native-localize”并使用“getCountry()”来代替。它只是返回没有语言的国家/地区,如下所示:“FR” (2认同)

bra*_*gan 6

为我工作上面的什么都没有,但这个组件。

console.log("Device Locale", DeviceInfo.getDeviceLocale()); // e.g en-US
Run Code Online (Sandbox Code Playgroud)

  • 并删除了 getDeviceLocale() (https://github.com/react-native-device-info/react-native-device-info/blob/master/CHANGELOG.md#300-beta1)以“删除react中的API重复-本地社区模块”;使用 https://github.com/zoontek/react-native-localize (3认同)

Rog*_*ris 5

function getLocale() {
  if (React.Platform.OS === 'android') {
    return I18n.locale;
  } else {
    return NativeModules.SettingsManager.settings.AppleLocale.replace(/_/, '-');
  }
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*man 0

您可能需要自己扩展 React Native 才能获取此信息。但是,根据您的用例,这个本地化组件(stefalda/ReactNativeLocalization)可能适合您。