【问题标题】:What's the best way to get device locale in react native (iOS)?在本机反应(iOS)中获取设备语言环境的最佳方法是什么?
【发布时间】:2015-11-02 00:05:36
【问题描述】:

类似于 Objective-C 中的 [NSLocale currentLocale]。

【问题讨论】:

    标签: react-native


    【解决方案1】:

    不需要外部库。你可以在 React 的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"
    

    为了对此进行测试,我将设备上的语言更改为法语。以下是您将在与语言环境相关的 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"]
        ...
    }
    

    【讨论】:

    • @DanielSteigerwald Android 尚不支持以这种方式访问​​设置。见Settings.android.js
    • 在 Android 上使用 NativeModules.I18nManager.localeIdentifier
    • @AralRoca 您是否偶然使用 Expo?在 Expo 上进行测试时,它看起来像是一个空对象,但在 iOS 模拟器和真实设备上一切正常。
    • 当本机应用使用 iOS13 SDK 构建时,这似乎在 iOS13 上中断。
    • @TomSwift 似乎这只是模拟器上的情况。它在我的 iOS 13 设备上运行良好。
    【解决方案2】:
    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
    

    【讨论】:

    • 从 iOS 13 开始,AppleLocale 似乎不再被定义。有人有 iOS 13 的解决方法吗?
    • @user3866793 NativeModules.SettingsManager.settings.AppleLanguages 包含一系列语言,请参阅stackoverflow.com/a/58063292
    • 从 ios 14 开始,AppleLocaleAppleLanguages 似乎都已定义。建议现在首先选择AppleLanguages,因为它支持特定于应用程序的首选语言功能。并使用可选链更好地实现向后兼容性
    【解决方案3】:

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

    I18n = require('react-native-i18n')
    locale = I18n.currentLocale()
    

    【讨论】:

    • 新版本的错误反应仅供参考。
    • 此软件包已弃用。您可以改用getCountry() 来使用react-native-localize。它只是返回没有语言的国家,例如:FR
    【解决方案4】:

    上面没有对我有用,但 this 组件。

    console.log("Device Locale", DeviceInfo.getDeviceLocale()); // e.g en-US
    

    【讨论】:

    【解决方案5】:
    function getLocale() {
      if (React.Platform.OS === 'android') {
        return I18n.locale;
      } else {
        return NativeModules.SettingsManager.settings.AppleLocale.replace(/_/, '-');
      }
    }
    

    【讨论】:

      【解决方案6】:

      iOS 13 解决方法:

      locale = NativeModules.SettingsManager.settings.AppleLocale // "fr_FR"
      console.log(" ==> Current settings: ", NativeModules.SettingsManager.settings)
      if (locale === undefined) {
          // iOS 13 workaround, take first of AppleLanguages array 
          locale = NativeModules.SettingsManager.settings.AppleLanguages[0]
          if (locale == undefined) {
                return "en" // default language
          }
      }

      【讨论】:

        【解决方案7】:

        您可以安装react-native-i18n并使用此功能:

        import React, { NativeModules } from 'react-native'
        ...
        function getLocale () {
          if (React.Platform.OS === 'android') {
            return NativeModules.RNI18n.getCurrentLocale(locale => locale.replace(/_/, '-'))
          } else {
            return NativeModules.RNI18n.locale.replace(/_/, '-')
          }
        }
        

        适用于 Android 和 iOS。

        【讨论】:

        • NativeModules 没有RNI18n(至少默认情况下)。我猜你添加了一个库。
        • 虽然在那个库中没有 getCurrentLocale 这样的东西。
        【解决方案8】:

        此代码是面向未来的

        import {NativeModules} from 'react-native';
        
        function getSystemLocale(): string {
          let locale: string;
          // iOS
          if (
            NativeModules.SettingsManager &&
            NativeModules.SettingsManager.settings &&
            NativeModules.SettingsManager.settings.AppleLanguages
          ) {
            locale = NativeModules.SettingsManager.settings.AppleLanguages[0];
            // Android
          } else if (NativeModules.I18nManager) {
            locale = NativeModules.I18nManager.localeIdentifier;
          }
        
          if (typeof locale === 'undefined') {
            console.log('Couldnt get locale');
            return 'en';
          }
        
          return locale;
        }
        
        export default {
          getSystemLocale,
        };
        

        【讨论】:

          【解决方案9】:

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

          【讨论】:

            【解决方案10】:

            我发现这个解决方案适用于 Android 和 iOS (RN 0.35)

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

            这可能会对某人有所帮助,但 iOS 不显示语言环境属性。它现在只显示 rtl 支持。

            【讨论】:

              【解决方案11】:

              如果你在 Expo 上开发......你可以使用:

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

              【讨论】:

                【解决方案12】:

                NativeModules 解决方案 can be changed 随着时间的推移由 Facebook 开发人员提供。
                由于这个原因,我准备了a component。 (目前仅适用于 Android)

                示例用法:

                import SystemSettings from 'react-native-system-settings'
                
                SystemSettings.get(
                    settings => console.log('settings: ', settings)
                )
                

                也可以使用promise-then:

                SystemSettings.get().then(settings => console.log('settings: ', settings)).done()
                

                也可以使用 ES7 async-await 方法!

                class App extends React.Component {
                    componentWillMount() {
                        this._loadInitialState()
                    }
                
                    _loadInitialState = async () => {
                        try {
                            let settings = await SystemSettings.get()
                            // Now settings variable would be filled and can be used!
                        } catch (error) {}
                    };
                }
                

                示例结果:

                {
                    densityDpi: 320,
                    fontScale: 1,
                    hardKeyboardHidden: "no",
                    keyboard: "qwerty",
                    keyboardHidden: "no",
                    localization: {
                        country: "US",
                        displayCountry: "United States",
                        displayLanguage: "English",
                        displayName: "English (United States)",
                        is24HourFormat: false,
                        language: "en",
                        locale: "en_US",
                        networkCountry: "US",
                        simCountry: "US",
                        timeZone: {
                            ID: "Europe/Amsterdam",
                            displayName: {
                                long: "Amsterdam Standard Time",
                                short: "GMT+01:00",
                            },
                            offset: 3600000
                        }
                    },
                    orientation: "portrait",
                    screenHeightDp: 615,
                    screenLayout: "normal",
                    screenWidthDp: 360,
                    smallestScreenWidthDp: 360,
                    uiModeType: "normal"
                }
                

                【讨论】:

                  【解决方案13】:

                  我个人更喜欢使用 react-native-i18n。 那么你可以在文档中这样使用..

                  import { getLanguages } from 'react-native-i18n'
                  
                  getLanguages().then(languages => {
                    console.log(languages) // ['en-US', 'en']
                  })
                  

                  链接:https://github.com/AlexanderZaytsev/react-native-i18n

                  【讨论】:

                  • 那个包'react-native-i18n'已经被弃用了请不要建议:)
                  【解决方案14】:
                  $ npm install --save react-native-localize
                  

                  --- 或 ---

                  $ yarn add react-native-localize
                  

                  import * as RNLocalize from "react-native-localize";
                  
                  console.log(RNLocalize.getLocales());
                  
                  let defaultLanguage = RNLocalize.getLocales()[0].languageCode;
                  
                  console.log('defaultLanguage', defaultLanguage);
                  

                  【讨论】:

                    【解决方案15】:

                    我正在使用react-native-i18n

                    为了访问我使用的设备语言:

                    import { getLanguages } from 'react-native-i18n';
                    
                    getLanguages().then(languages => {
                      console.log(languages); // ['en-US', 'en']
                    });
                    

                    这一切都在文档中。

                    【讨论】:

                      猜你喜欢
                      • 2014-04-11
                      • 2011-09-30
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2019-03-24
                      • 2023-03-21
                      相关资源
                      最近更新 更多