简体   繁体   English

react-hook-form 验证不适用于自定义字段数组

[英]react-hook-form validation not working with custom fields array

I am using react-hook-form with custom dynamic input fields array, it looks like the validation is working when I click on submit button, but it doesn't show the error messages, I am creating the state as:我正在使用带有自定义动态输入字段数组的 react-hook-form,当我单击提交按钮时,验证似乎正在工作,但它没有显示错误消息,我将状态创建为:

const [formFields, setFormFields] = useState([
{
  height: 45,
  label: "tv",
  placeholder: "555",
  name: "tv",
  maxWidth: 203,
  error: errors.tv,
  value: ""
},
{
  height: 45,
  label: "radio",
  placeholder: "90%",
  name: "radio",
  maxWidth: 126,
  error: errors.radio,
  value: ""
},
{
  height: 45,
  label: "instagram",
  placeholder: "90%",
  name: "instagram",
  maxWidth: 126,
  error: errors.instagram,
  value: ""
}

]); ]);

and creating the input as:并将输入创建为:

{formFields.map((item, index) => {
      return (
        <div key={index}>
          <TextInput
            name={item.name}
            label={item.label}
            height={item.height}
            placeholder={item.placeholder}
            error={item.error}
            value={item.value}
            inputRef={register({
              required: true
            })}
            onChange={fieldOnChange(index)}
          />
          {item.error && <span>Enter a valide value</span>}
        </div>
      );
    })}

you can check the demo你可以查看演示

any help please?有什么帮助吗?

It's because you formFields in useState.那是因为你在 useState 中形成了 formFields。 It runs only one time.它只运行一次。 Show it already captures errors value ie first initially value.显示它已经捕获了错误值,即第一个初始值。 You need to either use useEffect to keep track change of error value or change condition of item.error to directly errors.您需要使用 useEffect 来跟踪错误值的变化或将 item.error 的条件更改为直接错误。

react-hook-form uses its errors for validation ie in your case it should be react-hook-form使用其错误进行验证,即在您的情况下它应该是

{errors[item.name] && <span>Enter a valid value</span>}

Here is demo link : https://codesandbox.io/s/blue-shape-pv8jf这是演示链接: https : //codesandbox.io/s/blue-shape-pv8jf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM