访问react-hook-forms useFormContext中的表单错误

问题描述 投票:0回答:2

React-Hook-Form 版本号

7.51.2

问题

react-hook-forms
useFormContext
与此组件一起使用时:

文字输入

import { useFormContext } from "react-hook-form";
import { get } from "lodash";

export const TextInput = ({
  name,
  placeholder,
  disabled = false,
}) => {
  const { register, formState } = useFormContext();
  const field = register(name, {
    maxLength: { value: 5, message: "Too Long" },
  });

  const error = get(formState.errors, name);
  const label = error ? <label>{error.message}</label> : null;
  return (
    <div>
      <input
        data-testid={`form-input-${name}`}
        type="text"
        autoComplete="off"
        placeholder={placeholder}
        readOnly={disabled}
        {...field}
      />
      {label}
    </div>
  );
};

正确包装在提供程序中(包装输入的

div
的样式已将其删除,以提高视觉清晰度)

import { FormProvider, useForm } from "react-hook-form";
import { TextInput } from "./TextInput";
import { Submit } from "./Submit";


export const Form = ({ onSubmit, initialValues }) => {
  const methods = useForm({ defaultValues: initialValues });
  const submitFunction = methods.handleSubmit(onSubmit);
  return (
    <FormProvider {...methods}>
      <form onSubmit={submitFunction}>
        <div>
          <div>
            <TextInput
              name="name"
              placeholder="Name"
            />
          </div>
        </div>
        <Submit
          onClick={submitFunction}
          isFormValid={methods.formState.isValid}
        />
      </form>
    </FormProvider>
  );
};

无论出于何种原因,

formState: {errors}
中的错误都不会更新
onChange
/
onBlur
/
onFocus
。尽管验证返回无效时
formState : {isValid}
会进行更新。

通过我的调查,我注意到如果我将更改处理程序更新为

const handleChange = async (e) => {
  await trigger(fieldName)
  await onChange(e)
}

哪里

onChange
trigger
来自
react-hook-form
。 然后错误对象就会正确更新。

我制作了一个代码沙箱来说明它:

https://codesandbox.io/p/sandbox/cool-lalande-8n2kxp

任何帮助让它工作而不需要破解它来强制手动验证触发的帮助,我们将不胜感激。也许我正在做的事情的结构在某个地方是错误的?老实说,我在这里不知所措。

javascript reactjs forms react-hooks react-hook-form
2个回答
0
投票

这是因为 默认模式是

onSubmit
,但是您禁用了提交按钮(我可能会补充说这是一种不好的做法)。

如果将

mode:all
添加到
useForm()
那么它就可以工作


0
投票

原因在于模式。你应该将其更改为以下

const methods = useForm({ defaultValues: initialValues, mode: "all" });
© www.soinside.com 2019 - 2024. All rights reserved.