【问题标题】:How to use react-intl-tel-input in ReactJS如何在 ReactJS 中使用 react-intl-tel-input
【发布时间】:2021-12-02 11:15:40
【问题描述】:

您好,我从过去 1 个月开始学习 ReactJS,从过去 1 周开始,我遇到了一个问题。我正在使用带有 Firebase 电话身份验证的 React。我想使用 react-intl-tel-input 进行电话输入,但是当我安装软件包并在编写代码时编写代码时,我不明白如何以正确的方式使用代码并出现此类错误× TypeError: Cannot read properties of null (reading 'phoneNumber')。或者有时它给我这个错误× TypeError: Cannot read properties of null (reading 'e')我不希望用户必须用电话号码手动输入国家代码我希望用户可以简单地选择国家并在那里输入电话号码

任何人都可以请帮助我,我坚持了 1 周多,尝试了不同的 npm 包,也尝试使用 jQuery,但对我没有任何用处。

这是我的代码 (App.js)

import React from 'react'
import firebase from './firebase'
import IntlTelInput from 'react-intl-tel-input';
import 'react-intl-tel-input/dist/main.css';

class App extends React.Component {

  handleChange = (e) =>{
    const {name, value } = e.target
    this.setState({
        [name]: value
      })
  }
  
  configureCaptcha = () =>{
    window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
      'size': 'invisible',
      'callback': (response) => {
        // reCAPTCHA solved, allow signInWithPhoneNumber.
        this.onSignInSubmit();
        console.log("Recaptca varified")
      },
      defaultCountry: "IN"
    });
  }
  onSignInSubmit = (e) => {
    e.preventDefault()
    this.configureCaptcha()
    const phoneNumber = "+91" + this.state.mobile
    console.log(phoneNumber)
    const appVerifier = window.recaptchaVerifier;
    firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
        .then((confirmationResult) => {
          // SMS sent. Prompt user to type the code from the message, then sign the
          // user in with confirmationResult.confirm(code).
          window.confirmationResult = confirmationResult;
          console.log("OTP has been sent")
          alert("OTP has been sent")
        }).catch((error) => {
          // Error; SMS not sent
          // ...
          console.log("SMS not sent")
          alert("SMS not sent")
        });
  }
  onSubmitOTP = (e) =>{
    e.preventDefault()
    const code = this.state.otp
    console.log(code)
    window.confirmationResult.confirm(code).then((result) => {
      // User signed in successfully.
      const user = result.user;
      console.log(JSON.stringify(user))
      alert("User is verified")
      // ...
    }).catch((error) => {
      // User couldn't sign in (bad verification code?)
      // ...
    });
  }
  render() {
    return (
      <div>
        <h2>Login Form</h2>
        <form onSubmit={this.onSignInSubmit}>
          <div id="sign-in-button"></div>

           <IntlTelInput
                containerClassName="intl-tel-input"
                inputClassName="form-control"
                placeholder="Enter Your Number"
                value={this.state.phoneNumber}
                onPhoneNumberChange={this.handlePhoneChange} />
              
          {/* <input type="number" name="mobile" placeholder="Mobile number" required onChange={this.handleChange}/> */}
          <button type="submit">Submit</button>
        </form>

        <h2>Enter OTP</h2>
        <form onSubmit={this.onSubmitOTP}>
          <input type="number" name="otp" placeholder="OTP Number" required onChange={this.handleChange}/>
          <button type="submit">Submit</button>
        </form>
      </div>
    )
  }
}
export default App

【问题讨论】:

  • 公开分享您的 Firebase 连接信息不是一个好主意,因为任何人都可以使用它。可以在不添加连接信息的情况下发布您的 Firebase 代码,并且社区仍然可以重现该问题。

标签: javascript reactjs validation google-cloud-platform google-cloud-firestore


【解决方案1】:

这个库没有返回组件,正在粘贴我的组件。

phoneInput.js

import React, { useEffect, useState } from 'react';
import intlTelInput from 'intl-tel-input';
import clsx from 'clsx';
import 'intl-tel-input/build/css/intlTelInput.css';


export const PhoneInput=({disabled,...rest})=>{
//rest may include-name, onChange, etc
    const [options,toggleOptions]=useState({
        allowDropdown:true,
        autoHideDialCode:false,
        initialCountry: "auto",
        separateDialCode:true,
        nationalMode:false,
        hadInitialPlaceholder:true,
        utilsScript: process.env.REACT_APP_PHONE_UTIL_SCRIPT,
        geoIpLookup: async function(callback) {
           await fetch(process.env.REACT_APP_GEOIP_SERVICE)
           .then(res=>res.json())
           .then(({country})=>{
               callback(country)
           })},
        customPlaceholder: function(selectedCountryPlaceholder, selectedCountryData) {
            return "e.g. " + selectedCountryPlaceholder;
        },
    })
    useEffect(()=>{
        const input = document.querySelector("#signup-phone");
        if(!input) return;
        const iti=intlTelInput(input, {
            ...options
        });
        return()=>{
            iti.destroy();
        }
    },[])
    useEffect(()=>{
          toggleOptions(o=>({
              ...o,
              allowDropdown:!disabled
              //disable dropdown when disable flag is set
          }));
    },[disabled])
    return(
         <input
            disabled={disabled}
            type="tel"
            id="signup-phone"
            {...rest}
        />
    )
}

用于 signup.js

<PhoneInput 
   name="phone_no"
   onChange={handleChange}
   disabled={loading}
   error={errors['phone_no']}
  />

【讨论】:

    猜你喜欢
    • 2016-01-20
    • 2019-06-24
    • 2017-04-19
    • 2017-08-05
    • 2019-05-28
    • 1970-01-01
    • 2022-06-17
    • 2019-05-11
    • 2015-07-05
    相关资源
    最近更新 更多