【问题标题】:Accessing error from react-hook-form using reactstrap使用 reactstrap 从 react-hook-form 访问错误
【发布时间】:2021-09-23 14:30:01
【问题描述】:

我用 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

【问题讨论】:

    标签: javascript reactjs react-hook-form reactstrap


    【解决方案1】:

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

    您的表单需要具有相同的实例,您可以通过使用useformcontext 或将道具传递给组件来做到这一点。

    另外,你不需要控制器来做这件事, 这里是 codesandbox 展示了如何将 reactstrap 与 react-hook-form 一起使用。

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

    【讨论】:

    • 谢谢!我需要控制状态,因此我使用了 Controller。使用 useformcontext 并确保所有表单组件都使用相同的实例来完成这项工作。
    猜你喜欢
    • 2021-10-04
    • 2022-11-22
    • 2020-04-04
    • 2021-11-21
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 2021-04-10
    • 2021-08-18
    相关资源
    最近更新 更多