簡體   English   中英

react-hook-form 版本 7 驗證錯誤不起作用

[英]react-hook-form version 7 validation errors not working

我在使用新的 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 />但似乎不太明白。

任何幫助將不勝感激。 謝謝。

您只是忘記將 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM