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

使用react-hook-form时input输入框value显示[object Object]问题求解

问题原因

  • 核心错误来自你调用register("firstname")时传入的配置项里的value: { first_name }:你给输入框的value赋值了一个对象{first_name: ""},输入框渲染时会自动将对象转为字符串,就得到了你看到的[object Object]。
  • 额外冗余问题:你不需要单独用useState维护first_name状态,也不需要自己写onChangeFirstName处理函数,react-hook-form本身会托管所有表单字段的状态,自行绑定onChange、value等属性,两套状态管理逻辑同时存在反而会产生冲突。

修复后的代码

import React from "react";
import { useForm } from "react-hook-form";

function Account() {
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm({
    criteriaMode: "all",
    // 可在此处设置表单字段默认值
    defaultValues: {
      firstname: ""
    }
  });

  const onSubmit = (data) => {
    console.log(data);
    // 提交后清空字段直接用react-hook-form提供的reset方法即可
    reset({ firstname: "" });
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div className="p-5">
        <input
          className="border-2 border-black my-5 placeholder-gray-500 rounded-2xl h-12 p-5 outline-none"
          type="text"
          id="firstname"
          placeholder="First Name"
          {...register("firstname", {
            required: true,
            maxLength: 20,
          })}
        />
        {errors?.firstname?.type === "required" && (
          <p className="text-red-600 text-sm cursor-default">
            *First name is required
          </p>
        )}
        {errors?.firstname?.type === "maxLength" && (
          <p className="text-red-600 text-sm cursor-default">
            *First name cannot exceed 20 characters
          </p>
        )}
      </div>
      <input className="p-5 ml-5" type="submit" />
    </form>
  );
}

export default Account;

如果确实需要额外同步字段状态做其他逻辑,可以使用react-hook-form提供的watch方法监听字段变化,不需要自行绑定onChange事件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:06:03