首页 > 解决方案 > 以编程方式选择国家和拨号代码 - React-phone-input-2

问题描述

我在我的项目中使用 React-Phone-Input-2。代码如下。

<PhoneInput
        country={form.$("country").value}
        value={form.$("phone").value.countryCode}
        enableSearch={true}
        countryCodeEditable={false}
        placeholder=""
        onChange={(phone, country) => {
          debugger;
          field.set(phone);
        }}
        inputProps={{
          name: "countryCode",
          disabled: true,
          "data-test": "Address-phone.countryCode",
        }}
      />

这按预期工作。我可以手动选择一个国家,然后会显示国家标志和拨号代码。

现在我有一个国家下拉列表。当从国家下拉列表中选择一个国家时,它也应该以编程方式更改国家代码下拉列表

我在这里发现了一个类似的问题https://github.com/bl00mber/react-phone-input-2/issues/101。该演示包含一个示例,但找不到该示例的源代码。

关于如何实现这一点的任何想法?

标签: reactjs

解决方案


我也遇到过这个错误。这可能适用于您的用例。

import { Formik } from 'formik';
import PhoneInput from 'react-phone-input-2';
import 'react-phone-input-2/lib/material.css';
import countryList from 'country-calling-code';
/*
.
.
.
*/
<Formik
  initialValues={{
    country: ''
    phoneNumber: { countryCodeID: '', number: '' },
    phoneHolder: '',
  }}
  validationSchema={Yup.object().shape({
    phoneNumber: Yup.object({
      countryCodeID: Yup.string(),
      number: Yup.string(),
    }),
  })}
  onSubmit={async (
    values,
    { setErrors, setStatus, setSubmitting }
  ) => {
      try {
        /*
        you may clean your data here then add it to the database, etc.
        */
        setStatus({ success: true });
      } catch (err) {
        /*
        you may display error message here
        */
        setStatus({ success: false });
        setErrors({ submit: err.message });
      }
    }
  }}
>
  {({
    errors,
    handleBlur,
    handleChange,
    handleSubmit,
    setFieldValue,
    isSubmitting,
    touched,
    values,
  }) => (
    <form noValidate onSubmit={handleSubmit}>
      <TextField
        error={Boolean(touched.country && errors.country)}
        fullWidth
        helperText={touched.country && errors.country}
        label="Country"
        margin="normal"
        name="country"
        onBlur={handleBlur}
        onChange={(event) => {
          setFieldValue('state', '', true);
          setFieldValue('phoneNumber', {
            countryCodeID: getCountryID(event.target.value),
            number: values.phoneNumber.number,
          }, true);
          setFieldValue('phoneHolder', `${getCountryID(event.target.value)}${values.phoneNumber.number}`);
          handleChange(event);
        }}
        select
        value={values.country}
        SelectProps={{ native: true }}
        variant="outlined"
      >
        <option key="defult-option" value="Select country">
          Select country
        </option>
        {countryList.map((country) => (
          <option key={country.country} value={country.country}>
            {country.country}
          </option>
        ))}
      </TextField>
      <PhoneInput
        country='us'
        countryCodeEditable={false}
        onBlur={handleBlur}
        onChange={(phone, country) => {
          setFieldValue('country', country.name.normalize("NFD").replace(/[\u0300-\u036f]/g, ""));
          setFieldValue('phoneNumber', {
            countryCodeID: country.dialCode,
            number: phone.replace(country.dialCode, ''),
          });
        }}
        value={values.phoneHolder}
      />
      <Button
        color="primary"
        disabled={isSubmitting}
        fullWidth
        size="large"
        type="submit"
        variant="contained"
      >
        Submit country
      </Button>
    </form>
  )}
</Formik>


推荐阅读