【问题标题】:react-hook-form version 7 validation errors not workingreact-hook-form 版本 7 验证错误不起作用
【发布时间】:2021-04-09 15:20:36
【问题描述】:

我在使用新的 react-hook-form 版本 7 时遇到了验证错误问题,想知道是否有人可以提供帮助(参见下面链接的示例)。

https://codesandbox.io/s/react-hook-form-adapting-existing-form-forked-n3sis?file=/src/index.js

在我从 v6 更新到 v7 之前,这一切都可以正常工作。我改变了使用register 的方式,即{...register('name', {required: 'Add this'})} 而不是ref={register({required: 'Add this'})},并且现在更新了从formState 获取错误,即const { formState: { errors }} = useForm(); 而不是const { errors } = useForm();。

我很确定这与我使用受控组件有关,而不仅仅是原生 html <input />,但似乎无法弄清楚。

任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: reactjs react-hook-form


    【解决方案1】:

    您只是忘记将 props 和 ref 传递给输入组件。

    const Input = React.forwardRef(
      ({ error, id, label, required, ...props }, ref) => {
        return (
          <>
            <label htmlFor={id}>{label}</label>
            <input id={id} required={required} {...props} ref={ref} />
            <span style={{ color: "red" }}>{error}</span>
          </>
        );
      }
    );
    

    这是您的代码盒工作:https://codesandbox.io/s/react-hook-form-adapting-existing-form-forked-dpxie?file=/src/index.js

    【讨论】:

    • 感谢您的回答,很高兴这很简单。我真的很喜欢 react-hook-form 的简单性,并希望不是版本碰撞发生了巨大的变化,让生活变得更加复杂。
    • 它实际上需要哪些额外的道具,因为在这个例子中我们只是传播所有道具,而在我的团队世界例子中,我宁愿对可以传递的内容有更多的控制通过,即我不希望 className 被传递和添加并覆盖现有定义的样式。
    猜你喜欢
    • 2022-01-04
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-12
    • 1970-01-01
    相关资源
    最近更新 更多