【发布时间】:2021-06-29 18:46:08
【问题描述】:
我正在尝试对我的表单进行验证。我选择了“react-hook-form”库。但是我经常收到错误“Path.split 不是函数。即使使用了他们网站中给出的默认示例,我也遇到了同样的错误。 这是官网给出的默认代码。
import React from "react";
import { useForm } from "react-hook-form";
export default function App() {
const { register, handleSubmit, watch, errors } = useForm();
const onSubmit = data => console.log(data);
console.log(watch("example")); // watch input value by passing the name of it
return (
{/* "handleSubmit" will validate your inputs before invoking "onSubmit" */}
<form onSubmit={handleSubmit(onSubmit)}>
{/* register your input into the hook by invoking the "register" function */}
<input name="example" defaultValue="test" ref={register} />
{/* include validation with required or other standard HTML validation rules */}
<input name="exampleRequired" ref={register({ required: true })} />
{/* errors will return when field validation fails */}
{errors.exampleRequired && <span>This field is required</span>}
<input type="submit" />
</form>
);
}
【问题讨论】:
-
你能分享一个最小的CodeSandbox 来重现这个问题吗?
-
嗨@ArunKumarMohan 这是链接“codesandbox.io/live/ljesmy8”
-
看起来您共享的是会话 URL 而不是 CodeSandbox URL。我刚刚回答了一个类似的问题here,应该可以解决这个问题。将
ref={register}替换为{...register('example')}。 -
是的,它的工作原理。谢谢@ArunKumarMohan。我没有看到迁移文档。
-
不客气。
标签: react-hook-form