如何在React Native中获取设备的当前国家(适用于iOS和Android)?

11

我试图获取设备的当前国家,但没有找到任何信息。在React Native中是否有相关方法?我尝试使用react-native-device-info,但它也不支持获取这个信息,而之前的版本可以通过getDeviceCountry()方法来获取。现在,在最新版本中它会显示错误:

TypeError: _reactNativeDeviceInfo.default.getDeviceCountry不是一个函数。(在'_reactNativeDeviceInfo.default.getDeviceCountry()'中, '_reactNativeDeviceInfo.default.getDeviceCountry'未定义)


你能添加一段代码示例吗? - sanjar
5个回答

19
根据最新版本的 react-native-device-info 文档,他们已将部分API移至react-native-localize以减少在react-native-community模块中的重复。对我而言,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());

以及许多其他功能。有关详细说明,请通过给定的链接访问官方文档:react-native-localize


2

1

这解决了我的问题;

BREAKING CHANGE: 移除is24Hour、getTimezone、isAutoTimeZone和isAutoDateAndTime、getDeviceLocale、getDeviceCountry、getPreferredLocales,这是一项调查的结果。它消除了react-native-community模块中的API重复。

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

使用 yarn add

https://github.com/mikehardy/react-native-localize.git#e062f0d2dc3171dc18fdb7b7139d347ad03933dc 来维护isAutoTimeZone+isAutoDateAndTime,直到合并完成。


0
请使用此软件包来获取设备所在国家的信息。它具有不同类型的配置选项。 react-native-device-country 一些例子:
import DeviceCountry, {
  TYPE_ANY,
  TYPE_TELEPHONY,
  TYPE_CONFIGURATION,
} from 'react-native-device-country';

DeviceCountry.getCountryCode()
  .then((result) => {
    console.log(result);
    // {"code": "BY", "type": "telephony"}
  })
  .catch((e) => {
    console.log(e);
  });


DeviceCountry.getCountryCode(TYPE_TELEPHONY)
  .then((result) => {
    console.log(result);
    // {"code": "BY", "type": "telephony"}
  })
  .catch((e) => {
    console.log(e);
  });


DeviceCountry.getCountryCode(TYPE_CONFIGURATION)
  .then((result) => {
    console.log(result);
    // {"code": "BY", "type": "config"}
  })
  .catch((e) => {
    console.log(e);
  });

0

看起来这是React Native的一个bug,请检查他们的故障排除部分

以下是他们的建议:

似乎是由react-native link引起的bug。您可以在Xcode中手动删除libRNDeviceInfo-tvOS.a -> [您的iOS构建目标] -> 构建阶段 -> 链接二进制文件库。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接