使用 reactstrap 从 react-hook-form 访问错误

Accessing error from react-hook-form using reactstrap

我用 reactstrap 和 react-hook-form 创建了一个表单。为什么我的错误没有显示?

呈现文本输入的虚拟部分:

function DummySection() {
  const { control } = useForm();
  return (
    <div>
      <Controller
        name="dummyName"
        control={control}
        rules={{ required: true }}
        defaultValue=""
        render={({ field: { onChange, ref }, fieldState: { error } }) => (
          <TextInput onChange={onChange} innerRef={ref} error={error} />
        )}
      />
    </div>
  );
}

文本输入错误:

function TextInput({ onChange, value, innerRef, error }) {
  const updateText = (e) => {
    onChange(e);
    // do something else below
  };
  return (
    <div>
      <Input
        name="dummyName"
        type="text"
        onChange={(e) => updateText(e)}
        value={value}
        innerRef={innerRef}
      />
      {error && "Cannot be blank"}
    </div>
  );
}

提交按钮

function SubmitBtn() {
  const { handleSubmit } = useForm();
  const onSubmit = (data) => console.log(data);

  return <Button onClick={() => handleSubmit(onSubmit)()}>Submit</Button>;
}

谢谢。

Code Sandbox

@jamfie,您对每个组件使用不同的 useForm

您的表单需要具有相同的实例,您可以使用 useformcontext 或将 props 传递给组件来实现。

此外,您不需要控制器, 这里 codesandbox 展示了如何将 reactstrap 与 react-hook-form 一起使用。

您也可以在 github 期中关注 this answer