使用react-native-localize获取国家/地区电话前缀

dhxwm5r4  于 2023-01-05  发布在  React
关注(0)|答案(2)|浏览(345)

有没有办法用react-native-localize得到国家电话前缀?我可以得到国家代码,语言代码和其他东西,但我似乎不能得到电话前缀!
例如,在西班牙前缀是+34,在美国我认为是+1

iqjalb3h

iqjalb3h1#

您可以使用catamphetamine/libphonenumber-js。例如:

import getCountryCallingCode from 'libphonenumber-js'

getCountryCallingCode('RU') // returns '7'
getCountryCallingCode('IL') // returns '972'
42fyovps

42fyovps2#

您可以使用npm库,如country-telephone-data
下面是一个如何使用expo-localization执行此操作的示例...但原理与react-native-localize非常相似

import {allCountries} from 'country-telephone-data';
import * as Localization from 'expo-localization';
import React, {useEffect, useState} from 'react';
import {Text} from 'react-native';

export const CountryDialCode = () => {
  const [dialCode, setDialCode] = useState<string>();
  
  // This sets a state variable for dial code with an async call that looks up the localisation region and then uses that to look up the country dial code.
  useEffect(() => {
    const getCountryTelephoneCode = async () => {
      const {region} = await Localization.getLocalizationAsync();
      if (!region) return;
      const country = allCountries.find((country) => country.iso2 === region.toLowerCase());

      console.log(country);
      const _dialCode = country?.dialCode;
      setDialCode(_dialCode);
    };
    getCountryTelephoneCode();
  }, []);

  return <Text>{dialCode}</Text>;
};

相关问题