如果没有 name prop,react-hook-form 会工作吗?

Will react-hook-form work without the name prop?

我在 react-hook-form 文档中看到了这个例子 https://react-hook-form.com/api/useform/register Custom onChange, onBlur

const firstName = register('firstName', { required: true })
<input 
  onChange={(e) => {
    firstName.onChange(e); // method from hook form register
    handleChange(e); // your method
  }}
  onBlur={firstName.onBlur}
  ref={firstName.ref} 
/>

这里<input>里面没有name="firstName"

那么这个不提 name prop 也行吗?

需要name,否则RHF怎么知道这个值属于哪个字段呢?文档中的代码缺少 name 道具。如果省略代码,您可以确认代码不起作用:

<input
  // without the line below you can't see the submitted value
  name={firstName.name}
  onChange={(e) => {
    firstName.onChange(e); // method from hook form register
    handleChange(e); // your method
  }}
  onBlur={firstName.onBlur}
  ref={firstName.ref}
/>

我也遇到过没有 name 属性 RHF 无法工作的问题,但是,在当前版本(7.13.0)的文档中,代码示例已经没有了名称 道具。更新版本解决了我的问题。验证延迟也开始工作(useForm 挂钩中的 delayError 选项)