如何在 React Native(iOS 和 Android)中获取设备的当前国家/地区?

How to get current country of Device in React Native (iOS and Android)?

我正在尝试获取设备当前所在的国家/地区,但没有找到任何信息。在 React Native 中有什么可以这样做的吗? 我尝试使用 react-native-device-info 但它也不支持,但在以前的版本中可以通过 getDeviceCountry() 获取。现在最新版本显示错误:

TypeError: _reactNativeDeviceInfo.default.getDeviceCountry is not a function. (In '_reactNativeDeviceInfo.default.getDeviceCountry()', '_reactNativeDeviceInfo.default.getDeviceCountry' is undefined)

看起来这是 React Native 中的一个错误。请检查他们的 Troubleshooting section

这是他们的建议:

Seems to be a bug caused by react-native link. You can manually delete libRNDeviceInfo-tvOS.a in Xcode -> [Your iOS build target] -> Build Phrases -> Link Binary with Libraries.

根据 react-native-device-info for latest version, they have moved some of their apis to react-native-localize to reduce duplication in the react-native-community modules. react-native-localize 的文档,对我来说效果很好。

设置:

$ npm install --save react-native-localize
# --- or ---
$ yarn add react-native-localize

用法:

import * as RNLocalize from "react-native-localize";

console.log(RNLocalize.getLocales());
console.log(RNLocalize.getCurrencies());
console.log(RNLocalize.getCountry());
console.log(RNLocalize.getCalendar());
console.log(RNLocalize.getTemperatureUnit());
console.log(RNLocalize.getTimeZone());
console.log(RNLocalize.uses24HourClock());

还有更多。有关详细说明,请通过给定的link访问他们的官方文档:react-native-localize

它解决了我的问题;

重大更改: 删除 is24Hour、getTimezone、isAutoTimeZone 和 isAutoDateAndTime、getDeviceLocale、getDeviceCountry、getPreferredLocales

这是一项调查的结果。它删除了 API react-native-community 模块中的重复项

相关公关https://github.com/react-native-community/react-native-localize/pull/65

使用yarn add

https://github.com/mikehardy/react-native-localize.git#e062f0d2dc3171dc18fdb7b7139d347ad03933dc维持 isAutoTimeZone + isAutoDateAndTime 直到合并

接受的答案对我不起作用,可能是因为 https://github.com/zoontek/react-native-localize/issues/81

但是,Expo 的生态系统中有一些东西非常完美:

  1. expo install expo-localization
  2. import * as Localization from 'expo-localization';
  3. console.log(Localization.region);

编辑: 此处的文档 https://docs.expo.io/versions/latest/sdk/localization/#localizationregion