【问题标题】:Dynamically add errors when using useFieldArray with React Hook Form将 useFieldArray 与 React Hook Form 一起使用时动态添加错误
【发布时间】:2021-07-15 12:37:20
【问题描述】:

您将如何将自定义错误消息动态添加到使用 useFieldArray 生成的输入中?

这里非常简单的代码和框 - https://codesandbox.io/s/romantic-dubinsky-xd6f7?file=/src/App.js

通常我会写类似{errors.name && <p>This can't be empty</p>} 的东西,但是使用useFieldArray 输入的名称是动态生成的。我已经尝试过类似{errors.items.index.name && <p>This can't be empty</p>} 的方法,但这不起作用。

有什么建议吗?

【问题讨论】:

  • 这个括号语法太混乱了,因为他们的网站上没有提到它,而且它与字段名称不匹配我遇到了同样的 seterror 问题

标签: reactjs react-hook-form


【解决方案1】:

您非常接近,但您需要使用括号语法(以及可选链接来检查路径是否可用/有效):

{errors.items?.[index]?.name && <p>This can't be empty</p>}

【讨论】:

    猜你喜欢
    • 2021-05-08
    • 1970-01-01
    • 2022-10-13
    • 2020-11-23
    • 2022-11-22
    • 2020-04-04
    • 2022-06-12
    • 1970-01-01
    • 2020-11-15
    相关资源
    最近更新 更多