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

React-phone-input-2:选择国家码后自动聚焦失效问题求助

解决React-phone-input-2选择国家码后输入框不聚焦的问题

问题场景

使用react-phone-input-2组件时,通过inputProps={{autoFocus: true}}仅能实现组件首次挂载时的输入框聚焦,但切换国家码后输入框无法自动聚焦,与官方演示的正常表现不符。

可行解决方案

方法1:通过onChangeCountry回调手动触发聚焦

组件内置了onChangeCountry事件,可在国家码切换时触发回调,手动获取输入框DOM元素并执行聚焦操作:

  1. 先创建ref引用输入框:
import { useRef } from 'react';

const YourComponent = () => {
  const phoneInputRef = useRef(null);

  const handleCountrySwitch = () => {
    if (phoneInputRef.current) {
      phoneInputRef.current.focus();
    }
  };

  return (
    <PhoneInput
      ref={phoneInputRef}
      inputProps={{
          autoFocus: true
      }}
      onChange={(e, action) => phoneChange(e, action)}
      localization={i18n.language === 'ru' && ru}
      placeholder={placeholder}
      value={phoneNumber}
      buttonClass={styles.phoneButton}
      inputClass={styles.phoneInput}
      dropdownClass={styles.phoneDropdown}
      searchClass={styles.phoneSearch}
      searchPlaceholder={searchHolder}
      searchNotFound={searchFind}
      country={country}
      disableSearchIcon={true}
      enableSearch={true}
      autocompleteSearch={true}
      jumpCursorToEnd={true}
      onChangeCountry={handleCountrySwitch} // 添加国家切换回调
    />
  );
};

方法2:兼容jumpCursorToEnd的聚焦逻辑

你设置了jumpCursorToEnd={true},该属性可能与默认聚焦逻辑冲突,可在回调中同时实现光标跳转和聚焦:

const handleCountrySwitch = () => {
  if (phoneInputRef.current) {
    phoneInputRef.current.focus();
    // 手动将光标移至输入框内容末尾
    const inputVal = phoneInputRef.current.value;
    phoneInputRef.current.setSelectionRange(inputVal.length, inputVal.length);
  }
};

方法3:排查自定义样式干扰

检查inputClass={styles.phoneInput}对应的CSS样式,确认是否存在pointer-events: none、user-select: none等会阻断输入框交互的属性,这类样式可能导致聚焦失败。

验证方式

修改后切换国家码,输入框应自动聚焦,同时保持原有功能(如光标跳转、输入格式化)正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 06:12:44