简体   繁体   English

处理 react-hook-form 中的错误

[英]Handling errors in react-hook-form

According to documentation of react-hook-form I can use name of input element like this "xxx.yyy" and this will result in my prepared data to be根据 react-hook-form 的文档,我可以使用像“xxx.yyy”这样的输入元素的名称,这将导致我准备好的数据为

{ xxx: { yyy: value }}

But when I try to use this feature with 'errors' I cannot use it.但是当我尝试使用带有“错误”的此功能时,我无法使用它。 ie I cannot write below:即我不能在下面写:

{errors.xxx.yyy && <span>This field is required</span>}

because I get "Cannot read property 'yyy' of undefined".因为我得到“无法读取未定义的属性‘yyy’”。

Documentation says that I should use this chaining operator, ?.文档说我应该使用这个链接运算符,?。 , so I try it: ,所以我试试:

{errors?.xxx?.yyy && <span>This field is required</span>}

But nothing displays on the page if required input is omitted.但是如果省略了必需的输入,页面上将不会显示任何内容。 I can see that the mechanism blocks form from being submitted until I write something in this field, that is OK, but why I don't get the error message on the page?我可以看到该机制阻止提交表单,直到我在该字段中写入一些内容,这很好,但是为什么我没有在页面上收到错误消息?

it really depend which version you are using.这真的取决于您使用的是哪个版本。

V3: flat error object V3:平面错误对象

errors['xxx.yyyy']

V4: Nested errors object with better type support V4:具有更好类型支持的嵌套错误对象

errors?.xxx?.yyyy

we have also build a ErrorMessage component which you may find it useful.我们还构建了一个ErrorMessage组件,您可能会发现它很有用。

https://react-hook-form.com/api#ErrorMessage https://react-hook-form.com/api#ErrorMessage

Ok, I found answer myself.好的,我自己找到了答案。 I should use this form:我应该使用这种形式:

{errors['xxx.yyy'] && This field is required} {errors['xxx.yyy'] && 该字段为必填项}

Then everything works :-)然后一切正常:-)

you don't want to spend your coding time.你不想花你的编码时间。 you can use @hookform/error-message instead of code manually.您可以手动使用@hookform/error-message而不是代码。 it's very easy.这很容易。 it'll manage those errors.它会处理这些错误。 just pass the errors object given by react-hook-form and pass the property name that you want to display the error message.只需传递 react-hook-form 给出的错误对象并传递要显示错误消息的属性名称。

<ErrorMessage errors={errors} name="xxx.yyy" message="This is required" /> 

OR或者

if you want to customize your message as you want, you can render as you want like below.如果您想根据需要自定义您的消息,您可以按照您的需要进行render ,如下所示。 think that you want to bold and show invalid with red custom css class.认为您想用红色自定义 css 类加粗并显示无效。 then you can render as you want.然后您可以根据需要进行渲染。

<ErrorMessage render={({message}) => <div className="invalid-feedback d-block"><b> {message} </b></div>} errors={errors} name="xxx.yyy"/>

NPM https://www.npmjs.com/package/@hookform/error-message NPM https://www.npmjs.com/package/@hookform/error-message

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM