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

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

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

14条回答
  •  谎友^
    谎友^ (楼主)
    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"]
        ...
    }
    

提交回复
热议问题