【问题标题】:how to display country flags in custom react input phone in react?如何在自定义反应输入电话中显示国家标志?
【发布时间】:2022-07-10 01:47:46
【问题描述】:

最近我实现了一个自定义反应输入电话,但我无法在选项和所选国家/地区显示国家/地区标志。 实际上,我不能直接使用 PhoneInput,因为我需要提取国家并将其标签发送到服务器(例如:'US')。 如果您对在自定义输入中显示标志或在默认 PhoneInput 中提取选定国家/地区标签有任何想法,请回答。

谢谢

这是我的代码行:

import Input, {
  getCountries,
  getCountryCallingCode,
} from "react-phone-number-input/input";
import en from "react-phone-number-input/locale/en.json";
import "react-phone-number-input/style.css";

const RegisterForm = () => {
  const [onFocuseInput, setOnFocuseInput] = useState("");
  const [phoneNumber, setPhoneNumber] = useState();
  const [country, setCountry] = useState();

const CountrySelect = ({ value, onChange, labels, ...rest }) => (
    <select
      {...rest}
      value={value}
      onChange={(event) => {
        onChange(event.target.value || undefined);
      }}
    >
      <option value="">country</option>
      {getCountries().map((country) => (
        <option key={country} value={country}>
          {labels[country]} +{getCountryCallingCode(country)}
        </option>
      ))}
    </select>
  );


 <div className="mb-6 flex">
          <CountrySelect
            className={`border-b-2 bg-none outline-none w-1/4 text-xs ${
              onFocuseInput === "country"
                ? "border-blue-700 "
                : "border-gray-300"
            }`}
            labels={en}
            value={country}
            onChange={setCountry}
            name="countrySelect"
            onFocus={() => setOnFocuseInput("country")}
          />
          <Input
            className={`${
              onFocuseInput === "phoneNumber"
                ? "focusedInput w-full"
                : "registerInput w-full"
            }`}
            placeholder="phoneNumber"
            dir="ltr"
            country={country}
            value={phoneNumber}
            onChange={setPhoneNumber}
            name="phoneNumber"
            onFocus={() => setOnFocuseInput("phoneNumber")}
            required
          />
        </div>
        {loading ? (
          <div className="flex justify-center items-center my-5 bg-red-600 p-4 rounded-full">
            <div
              className="spinner-border animate-spin inline-block w-8 h-8 border-4 border-blue-700 border-t-white rounded-full"
              role="status"
            ></div>
          </div>
  );
};

export default RegisterForm;

【问题讨论】:

    标签: javascript reactjs typescript


    【解决方案1】:

    您可以解析输入字段中输入的值并获取国家代码。你可以使用libphonenumber-js

    import React, { useState } from "react";
    import Input, {parsePhoneNumber} from "react-phone-number-input";
    import "react-phone-number-input/style.css";
    
    const RegisterForm = () => {
      const [onFocuseInput, setOnFocuseInput] = useState("");
      const [phoneNumber, setPhoneNumber] = useState("");
      const [country, setCountry] = useState("");
    
      const handleChange = (value) => {
        let p = "";
        let c = "";
        const parsedValue = parsePhoneNumber(value ? value : "", 'US');
        if (parsedValue) {
          p = parsedValue.nationalNumber;
          c = parsedValue.countryCallingCode;
        }
        setPhoneNumber(p);
        setCountry(c);
      };
    
      return (
        <div>
          <div className="mb-6 flex">
            <Input
              className={`${
                onFocuseInput === "phoneNumber"
                  ? "focusedInput w-full"
                  : "registerInput w-full"
              }`}
              placeholder="phoneNumber"
              dir="ltr"
              defaultCountry="US"
              limitMaxLength
              onChange={handleChange}
              name="phoneNumber"
              onFocus={() => setOnFocuseInput("phoneNumber")}
              required
            />
          </div>
        </div>
      );
    };
    
    export default RegisterForm;
    

    【讨论】:

    • 它解决了我的什么问题?我希望电话号码和国家/地区标签与我在代码中编写的 PhoneInput 或国家/地区中的国家/地区标志分开。
    • 我编辑我的答案并添加详细的示例代码
    • 我不需要国家代码兄弟。我之前有国家代码。无论如何,我需要国旗和国家标签,谢谢。
    • 您将国家/地区标签转换为 parsedValue.country,可通过 URL 访问标志,例如 purecatamphetamine.github.io/country-flag-icons/3x2{XX}.svg(将 XX 更改为国家/地区标签)@SaeidShoja
    【解决方案2】:

    “onCountryChange”事件,可以通过添加onCountryChange事件监听来获取countryCode。附上找代码供参考。

    import * as React from "react";
    import { useForm, Controller } from "react-hook-form";
    
    import PhoneInput, {
      parsePhoneNumber,
      getCountryCallingCode
    } from "react-phone-number-input";
    
    import "react-phone-number-input/style.css";
    import "./styles.css";
    
    export default function App() {
      const [phoneCountryCode, phoneCountryCodeSetter] = React.useState("DE");
    
      const {
        control,
        formState: { errors },
        handleSubmit
      } = useForm();
    
      const onSubmit = (data) => console.log(data);
    
      return (
        <>
          <form onSubmit={handleSubmit(onSubmit)}>
            <Controller
              name="cellphone"
              rules={{
                validate: {
                  isValid: (value) => {
                    if (value) {
                      const callingCode = getCountryCallingCode(phoneCountryCode);
                      if (!new RegExp(`^\\+${callingCode}$`).test(value)) {
                        return !!parsePhoneNumber(value);
                      }
                    }
                    return true;
                  }
                }
              }}
              control={control}
              render={({ field }) => (
                <PhoneInput
                  {...field}
                  onCountryChange={(v) => phoneCountryCodeSetter(v)}
                  limitMaxLength={true}
                  international={true}
                  defaultCountry="DE"
                />
              )}
            />
            {errors.cellphone?.type === "isValid" && (
              <span className="validation-message">Enter a valid phone number</span>
            )}
            <input type="submit" />
          </form>
        </>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-18
      • 2012-11-04
      • 1970-01-01
      • 2022-01-12
      • 2020-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多