You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ReactJS中使用react-intl-tel-input实现带国家选择的手机号输入

报错原因及修复方案

核心问题点

  • 类组件未初始化state,导致首次渲染访问this.state.phoneNumber时读取null属性报错
  • 未定义handlePhoneChange方法,react-intl-tel-input的onPhoneNumberChange回调参数不是标准DOM事件,不能用普通input的handleChange处理,这也是触发Cannot read properties of null (reading 'e')报错的原因
  • 提交手机号时硬编码印度区号+91,没有使用组件返回的带选中国家区号的完整手机号,浪费了国家选择功能
  • 绑定的state变量名和提交时读取的变量名不匹配

修正后完整代码

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 {
  // 新增:初始化state,避免访问null属性
  state = {
    phoneNumber: '',
    otp: ''
  }

  // 处理普通输入框变更(OTP字段用)
  handleChange = (e) =>{
    const {name, value } = e.target
    this.setState({
      [name]: value
    })
  }

  // 新增:处理手机号输入组件的变更回调
  handlePhoneChange = (status, value, countryData, fullNumber) => {
    // fullNumber是带选中国家区号的完整手机号,直接存储即可
    this.setState({
      phoneNumber: fullNumber
    })
  }
  
  configureCaptcha = () =>{
    window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('sign-in-button', {
      'size': 'invisible',
      'callback': (response) => {
        this.onSignInSubmit();
        console.log("Recaptca varified")
      },
      defaultCountry: "IN"
    });
  }
  onSignInSubmit = (e) => {
    e.preventDefault()
    this.configureCaptcha()
    // 改:直接使用state中存储的完整带区号手机号,无需手动拼接前缀
    const phoneNumber = this.state.phoneNumber
    console.log(phoneNumber)
    const appVerifier = window.recaptchaVerifier;
    firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
        .then((confirmationResult) => {
          window.confirmationResult = confirmationResult;
          console.log("OTP has been sent")
          alert("OTP has been sent")
        }).catch((error) => {
          console.log("SMS not sent", error)
          alert("SMS not sent")
        });
  }
  onSubmitOTP = (e) =>{
    e.preventDefault()
    const code = this.state.otp
    console.log(code)
    window.confirmationResult.confirm(code).then((result) => {
      const user = result.user;
      console.log(JSON.stringify(user))
      alert("User is verified")
    }).catch((error) => {
      console.log("OTP verification failed", error)
    });
  }
  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} />
              
          <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

额外说明

  • 提交前可增加手机号有效性判断,过滤空值、格式错误的号码,减少不必要的接口请求
  • defaultCountry参数可以根据你的需求调整默认选中的国家

内容的提问来源于stack exchange,提问作者MOHAMMAD ZEESHAN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 08:36:03