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

Next.js 14中PhoneInputWithCountry组件无法通过事件设置值求助

解决Next.js 14中PhoneInputWithCountry组件值无法设置的问题

核心问题在于:当你用react-hook-form的control属性绑定PhoneInputWithCountry组件时,组件状态由react-hook-form管理,而非你自定义的useState。直接修改tel的state无法同步到表单组件,导致设置值无效。

解决方案

改用react-hook-form提供的setValue方法更新表单字段值,移除自定义useState,让表单库接管状态管理:

import { useForm } from "react-hook-form";
import PhoneInputWithCountry from "react-phone-number-input/react-hook-form";

export default function Home() {
  const { control, setValue, watch } = useForm();
  const specialTel = "+1 604 111 1111";
  // 如需获取当前输入值,用watch监听字段
  const tel = watch("tel");

  const fillValue = (isChecked: boolean) => {
    if (isChecked) {
      setValue("tel", specialTel);
    } else {
      // 取消勾选时可选择清空值
      setValue("tel", "");
    }
  };

  return (
    <>
      <div className="w-[150px]" style={{ width: "150px" }}>
        <label htmlFor="specialTel">设置指定号码</label>
        <input
          id="specialTel"
          type="checkbox"
          onChange={(event) => fillValue(event.target.checked)}
        />
        <PhoneInputWithCountry
          name="tel"
          control={control}
          countries={["CA"]}
          addInternationalOption={false}
          defaultCountry="CA"
          min={10}
          international={true}
          limitMaxLength={true}
        />
      </div>
    </>
  );
}

关键修改点

  • 移除自定义useState,通过setValue直接操作react-hook-form的表单状态
  • 去掉组件上的value和defaultValue属性,由control接管状态同步
  • 若需获取当前输入值,使用watch("tel")监听字段变化

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 12:07:03