【问题标题】:Updating errors in react hook form更新反应钩子形式的错误
【发布时间】:2021-06-03 21:29:42
【问题描述】:

所以我创建了一个自定义输入包装器,它接收来自 react-hook-form 的几个道具。

这是我的文本输入

import { useForm } from 'react-hook-form'

const {
  register, 
  formState: { 
    errors 
  },
} = useForm();

<TextInput
  id={'password'}
  errors={errors}
  register={register}
  options={{
    minLength: {
      message: 'Please pick password longer than 8 characters',
      value:   8,
    },
    required: 'Password is required',
  }}
  type={"password"}
  placeholder={'Enter password'}
/>

在我的组件中,我传递了这些道具,如果选项中的任何条件不满足,我会尝试显示错误消息。

<div>
  <input
    error={errors[id] ? true : false}
    placeholder={placeholder}
    type={type}
    {...register(id, options)}
  />
  {
    errors[id] &&
      <div>
        { errors[id].message }
      </div>
  }
</div>

只有在我提交了之前的表单并更新了文本字段时才会出现错误,如何让它们在提交时显示?

【问题讨论】:

    标签: javascript reactjs typescript react-hooks react-hook-form


    【解决方案1】:

    您没有显示表单的结构, 但你可以这样做:

    import "./styles.css";
    import { useForm } from "react-hook-form";
    
    const TextInput = ({errors, placeholder, type, id, register, options}) => {
      return (
        <div>
          <input
            // error={errors[id] ? true : false}
            placeholder={placeholder}
            type={type}
            {...register(id, options)}
          />
          {
            errors[id] &&
              <div>
                { errors[id].message }
              </div>
          }
        </div>
      )
    }
    
    export default function App() {
      const {
        register, 
        handleSubmit,
        formState: { 
          errors 
        }
      } = useForm();
    
      const onSubmit = data => {
        console.log(data);
      }
    
      return (
    
          <form onSubmit={handleSubmit(onSubmit)}>
            <TextInput
              id={'password'}
              errors={errors}
              register={register}
              options={{
                minLength: {
                  message: 'Please pick password longer than 8 characters',
                  value:   8,
                },
                required: 'Password is required',
              }}
              type={"password"}
              placeholder={'Enter password'}
            />
            <button>submit</button>
          </form>
        
      )
      
    }
    

    这是sandBox

    注意:
    如果你的表单是嵌套的,你可以使用useformcontext
    你可以在docs阅读它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-01
      • 1970-01-01
      • 2020-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-25
      相关资源
      最近更新 更多