【问题标题】:Can't get value form input in react-hook-form无法在 react-hook-form 中获取值形式输入
【发布时间】:2021-08-07 05:05:48
【问题描述】:

我正在使用react-hook-form

我有一个来自我的数据库的值,用于在初始加载时设置输入值。当我提交表单时,我失去了价值。

我该如何解决这个问题?

const FormCV = () => {
 const { register } = useForm();
 const onSubmit = (data) => {alert(JSON.stringify(data))};
 return (
   <form onSubmit={handleSubmit(onSubmit)}>
     <input
      type="text"
      value={newForm.companyname}
      {...register("companyname")}
     />
    </form>
  );
};

【问题讨论】:

  • 你能在codesandbox中分享一个可执行代码吗?

标签: reactjs react-hook-form


【解决方案1】:

您需要删除 value 属性并在 react-hook-form 的 registerdefaultProps 中设置 value


选项 1

register 中设置单个值。

const { register } = useForm(); // don't need default values set here
<input {...register("companyname",{ value: newForm.companyname })} ...otherProps />

选项 2

使用defaultValues设置输入值

const defaultValues = { companyname: newForm.companyname };
const { register } = useForm({ defaultValues });
<input {...register("companyname")} ...otherProps /> // don't need to set the value here

【讨论】:

  • 感谢您抽出宝贵时间提供答案。这个答案真的很有帮助。
猜你喜欢
  • 2021-11-11
  • 2023-03-17
  • 2022-06-13
  • 1970-01-01
  • 1970-01-01
  • 2018-04-19
  • 2022-07-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多