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

React中react-hook-form的Controller导致PhoneInput无法聚焦问题

解决react-phone-number-input + react-hook-form Controller组件聚焦失效问题

问题原因

  1. 属性绑定错误:react-hook-form的Controller返回的field对象包含focus、ref等方法,直接通过{...field}传递给PhoneInput时,这些方法会绑定到PhoneInput渲染的外层div上,而实际可聚焦的是内部的<input class="PhoneInputInput">元素,导致聚焦逻辑失效。
  2. CSS选择器错误:你的.customPhoneInput:focus是给外层div加的聚焦样式,但实际获得焦点的是内部input,所以样式不会触发。

解决方案

1. 正确传递Controller的field到内部输入框

使用PhoneInput的inputProps属性,将field中的属性传递给内部的真实input元素,确保聚焦逻辑绑定到正确的元素上:

修改后的代码:

<Controller
  type="tel"
  control={control}
  rules={{ required: true }}
  name="phone"
  render={({ field }) => (
    <PhoneInput
      international
      withCountryCallingCode
      className={`border border-opacity-20 placeholder:opacity-50 border-[#2E2B27] px-3 py-3 placeholder-[#2E2B27] text-[#2E2B27] bg-white font-opensans font-normal text-lg rounded-lg w-full ease-linear transition-all duration-150`}
      placeholder="83457 92890"
      defaultCountry="IN"
      // 将field属性传递给内部input
      inputProps={{
        ...field,
        placeholder: "83457 92890"
      }}
    />
  )}
/>

2. 修正CSS聚焦样式

针对内部的input元素或者使用:focus-within伪类来实现样式变化:

方式一:直接给内部input加样式

.PhoneInputInput:focus {
  opacity: 0.2;
  /* 可添加其他聚焦样式 */
}

方式二:通过父元素控制外层样式

如果需要聚焦时修改外层div的样式,使用:focus-within伪类:

.customPhoneInput:focus-within {
  opacity: 0.2;
  /* 可添加其他外层样式 */
}

验证效果

修改后,点击或按Tab键时,内部input会正确获得焦点,聚焦样式正常触发,同时react-hook-form的表单控制逻辑也能正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 10:12:49