[英]Dynamic extensions to errors object in react-hook-form
React-hook-form
provides an errors object through useForm. React-hook-form
通过 useForm 提供了一个错误 object。 Since checking for error is dependent on the name attribute of the input field (something like {errors.title?.type === "require" && <p>Title required</p>}
) and I create the input field names dynamically, I need to somehow set the extension dynamically too.由于检查错误取决于输入字段的名称属性(类似于
{errors.title?.type === "require" && <p>Title required</p>}
)并且我动态创建输入字段名称,我也需要以某种方式动态设置扩展名。
{errors.title?.type === "require" && <p>Title required</p>}
is created together with the form fields. {errors.title?.type === "require" && <p>Title required</p>}
与表单字段一起创建。 Each new form field has one to validate it.每个新的表单域都有一个来验证它。
Because errors.title
could be errors.title_3
, so:因为
errors.title
可能是errors.title_3
,所以:
{errors.
title <--This part would need to be dynamic, maybe dependant on props or state etc.
标题 <--这部分需要是动态的,可能取决于道具或 state 等。
?.type === "require" && <p>Title required</p>}
I tried really hard to solve this propblem.我非常努力地解决这个问题。 I tried different variations of using
eval()
to get a string to function as logic.我尝试了使用
eval()
来获取 function 的字符串作为逻辑的不同变体。 It created the logic dynamically but it didn't rerender when a form field error occured to display the error.它动态地创建了逻辑,但是当出现表单字段错误以显示错误时它没有重新呈现。 So
<p>Title required</p>
was created.所以
<p>Title required</p>
被创建了。 Don't know why.不知道为什么。
I also tried to make it work trough useState and useEffect but I couldn't.我也试图通过 useState 和 useEffect 让它工作,但我做不到。 I searched the web for solutions but didn't find any.
我在 web 中搜索了解决方案,但没有找到任何解决方案。
The solutions might be through react-hook-form, React or the solution might just be based in javascript.解决方案可能是通过 react-hook-form、React 或解决方案可能只是基于 javascript。 I really don't know.
我真的不知道。 I'm just confused after hours of trying.
经过几个小时的尝试,我只是感到困惑。
Thank you in advance.先感谢您。
I came across this same issue and i was able to resolve it using the Error Message component .我遇到了同样的问题,我能够使用错误消息组件解决它。 Below is a code snippet.
下面是一个代码片段。
import { ErrorMessage } from "@hookform/error-message";从“@hookform/error-message”导入 { ErrorMessage };
<ErrorMessage
errors={errors}
name={dynamicNameGoesHere}
/>
I hope this helps someone.我希望这可以帮助别人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.