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

react-phone-number-input设置inputComponent属性后输入触发报错求助

解决react-phone-number-input搭配Antd Input组件的运行时错误

问题场景

使用react-phone-number-input处理手机号输入时,为了匹配Antd其他输入组件的样式,直接设置inputComponent={Input}解决了样式问题,但输入框按键时触发运行时错误,报错信息包括:

  • element.hasAttribute is not a function
  • Cannot read properties of undefined (reading 'length')

原代码示例:

<Form.Item name="telefonNo" label={t("kisi.telefonNo")}>
  <PhoneInput defaultCountry="TR" placeholder={t("kisi.telefonNoHint")} inputComponent={Input} />
</Form.Item>

解决方案

react-phone-number-input的inputComponent参数需要接收能暴露原生input DOM元素引用的组件,而Antd的Input是封装后的组件,直接传入会导致内部无法正确获取原生DOM节点。通过forwardRef包装Antd Input,确保传递正确的DOM引用即可解决问题。

步骤1:包装Antd Input组件

使用React的forwardRef包装Antd Input,将原生input的引用传递给父组件:

import { Input } from 'antd';
import { forwardRef } from 'react';

const AntdPhoneInput = forwardRef((props, ref) => {
  return <Input {...props} ref={ref} />;
});

步骤2:使用包装后的组件

将包装好的AntdPhoneInput传入PhoneInput的inputComponent:

<Form.Item name="telefonNo" label={t("kisi.telefonNo")}>
  <PhoneInput 
    defaultCountry="TR" 
    placeholder={t("kisi.telefonNoHint")} 
    inputComponent={AntdPhoneInput} 
  />
</Form.Item>

原因说明

react-phone-number-input内部需要直接调用原生input元素的方法和属性(如hasAttribute、读取输入值的length),Antd默认的Input组件不会直接暴露原生DOM节点的引用,通过forwardRef包装后,PhoneInput能正确获取到原生input元素,从而避免运行时错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 19:35:59