What's the best way to get device locale in react native (iOS)?

后端 未结 14 1605
清歌不尽
清歌不尽 2020-12-13 03:35

Something similar to [NSLocale currentLocale] in Objective-C.

相关标签:
14条回答
  • 2020-12-13 04:11
    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
    
    0 讨论(0)
  • 2020-12-13 04:15

    I found this solution for Android and iOS (RN 0.35)

    import React, {NativeModules} from 'react-native';
    
    if (NativeModules.I18nManager) {
        const {localeIdentifier, isRTL} = NativeModules.I18nManager;
    }
    

    May be this will help to someone, but iOS not shows locale property. It shows only rtl support now.

    0 讨论(0)
  • 2020-12-13 04:16

    There's no need for an external library. You can find what you're looking for in React's Native Modules

    import { NativeModules } from 'react-native'
    
    // iOS:
    const locale = NativeModules.SettingsManager.settings.AppleLocale ||
                   NativeModules.SettingsManager.settings.AppleLanguages[0] // "fr_FR"
    
    // Android:
    const locale = NativeModules.I18nManager.localeIdentifier // "fr_FR"
    

    To test this, I changed the language on my device to French. Here's a sample of what you'll find in the NativeModules.SettingsManager.settings object related to locale:

    {
        ...
        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"]
        ...
    }
    
    0 讨论(0)
  • 2020-12-13 04:19

    if you develop over Expo... you can use:

    console.log(await NativeModules.ExponentUtil.getCurrentLocaleAsync());
    console.log(await NativeModules.ExponentUtil.getCurrentDeviceCountryAsync());
    console.log(await NativeModules.ExponentUtil.getCurrentTimeZoneAsync());

    0 讨论(0)
  • 2020-12-13 04:20

    Nothing of the above worked for me, but this component.

    console.log("Device Locale", DeviceInfo.getDeviceLocale()); // e.g en-US
    
    0 讨论(0)
  • 2020-12-13 04:20

    You may need to extend react native yourself to get this info. But, depending on your use case, this localization component (stefalda/ReactNativeLocalization) may work for you.

    0 讨论(0)
提交回复
热议问题