简体   繁体   English

如何在 ReactJS 中使用 react-intl-tel-input

[英]How to use react-intl-tel-input in ReactJS

Hello I have started learning ReactJS from past 1 months and from last 1 week i stuck with a problem.您好,我从过去 1 个月开始学习 ReactJS,从过去 1 周开始,我遇到了一个问题。 I am using React with Firebase Phone Authentication.我正在使用带有 Firebase 电话身份验证的 React。 I want to use react-intl-tel-input for taking Phone input but when i install the package and write the code while writing i don't understand how to use the code in right way and getting this type of error × TypeError: Cannot read properties of null (reading 'phoneNumber') .我想使用 react-intl-tel-input 进行电话输入,但是当我安装 package 并在编写代码时编写代码时,我不明白如何以正确的方式使用代码并出现此类错误× TypeError: Cannot read properties of null (reading 'phoneNumber') or some times its give me this error × TypeError: Cannot read properties of null (reading 'e') I don't want that user have to type there country code manually with phone Number I want that user can simply select there country and type there phone number或者有时它给我这个错误× TypeError: Cannot read properties of null (reading 'e')有电话号码像这样

can Any one Please Help me i stuck in this from more than 1 week tried different npm packages also try to use jQuery but nothing work for me.任何人都可以请帮助我,我坚持这个超过 1 周尝试了不同的 npm 包也尝试使用 jQuery 但对我没有任何作用。

this is my code ( App.js )这是我的代码( 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

This library does not return a component, am pasting my component.该库不返回组件,正在粘贴我的组件。

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}
        />
    )
}

Utilised in signup.jssignup.js使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM