React Hooks Form:提交时未定义值

jos*_*faz 14 javascript reactjs react-hooks react-hook-form

我从文档中获取了示例:

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

export default function App() {
  const { register, handleSubmit, watch, formState: { errors } } = useForm();
  const onSubmit = data => console.log(data);

  console.log(watch("example")); 

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input defaultValue="test" {...register("example")} />
      <input type="submit" />
    </form>
  );
}
Run Code Online (Sandbox Code Playgroud)

但在每次更改或提交时,我都会得到undefined每个字段

在此输入图像描述

我尝试再次安装该库,但没有任何变化,并且到处都未定义......似乎是注册功能的问题。有人遇到同样的问题吗?

GG.*_*GG. 16

就我而言,这是一个错字:

<input defaultValue="test" {...(register('name'), { required: true })} />

// submit => { name: undefined }
Run Code Online (Sandbox Code Playgroud)

代替:

<input defaultValue="test" {...(register('name', { required: true }))} />

// submit => { name: "test" }
Run Code Online (Sandbox Code Playgroud)

希望它可以帮助别人。

  • +10!! 这是一个很容易犯的错误。我必须仔细找出你的代码中的差异! (2认同)

kno*_*fel 8

在 v7 中, 的用法发生了register变化,如评论中所述。如果你还需要使用v6,你就得这样写:

function App() {
  const { register, handleSubmit, watch, formState: { errors } } = useForm();
  const onSubmit = data => console.log(data);

  console.log(watch("example")); 

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input defaultValue="test" name="example" ref={register} />
      <input type="submit" />
    </form>
  );
}
Run Code Online (Sandbox Code Playgroud)

文档 v6

编辑 React Hook 表单 - 注册 v6