javascript React钩表:提交时未定义值

jtjikinw  于 2023-03-06  发布在  Java
关注(0)|答案(6)|浏览(114)

我举了documentation的例子:

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>
  );
}

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

我试着再次安装库,但是没有任何变化,到处都是未定义的...似乎是注册函数的问题。有人遇到过同样的问题吗?

nhaq1z21

nhaq1z211#

在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>
  );
}

文档v6

bvhaajcl

bvhaajcl2#

在我的情况下,这是一个错字:

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

// submit => { name: undefined }

取代:

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

// submit => { name: "test" }

希望它能帮助其他人。

sbtkgmzw

sbtkgmzw3#

在我的例子中,我使用的是一个Controller,所以要修复Undefined值,我只需要将defaultValues传递给useForm。https://react-hook-form.com/api/useform/watch

const { register, handleSubmit, control, setValue} = useForm<MyFormValues>({
    defaultValues : {
      receiveUpdates: false
    }
  });

<Controller
  control={control}
  name="receiveUpdates"
  render={({ field }) => (
    <FormControlLabel
      control={
        <Checkbox
          ref={field.ref}
          checked={field.value}
          onChange={field.onChange}
        />
      }
      label="Receive Email Updates?"
      labelPlacement="start"
    />
  )}
/>
6za6bjd0

6za6bjd04#

我在使用reactstrap的输入组件时遇到了这个问题。使用该组件使我所有的值都未定义。我将输入切换为正常输入,并能够读入值
之前:

<Input 
                placeholder="Password"
                type="password"
                id="password"
                defaultValue=""
                {...register('password')}
                required
              />

固定:

<input 
                placeholder="Password"
                type="password"
                id="password"
                defaultValue=""
                {...register('password')}
                required
              />
vhmi4jdf

vhmi4jdf5#

在我的例子中,我安装了类似“npm i react-hook-form”的东西,我不知道为什么,但是它安装的是^6.15.8版本,我删除了它,然后再试一次,然后它被正确安装。

643ylb08

643ylb086#

对我起作用的是删除我的<input />上的ref

相关问题