简体   繁体   English

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

[英]Accessing error from react-hook-form using reactstrap

I created a form with reactstrap and react-hook-form.我创建了一个带有 reactstrap 和 react-hook-form 的表单。 Why are my errors not displaying?为什么我的错误没有显示?

Dummy section which renders text input:呈现文本输入的虚拟部分:

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>
  );
}

Text input with error:文本输入错误:

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>
  );
}

Submit Button提交按钮

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

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

Thanks.谢谢。

Code Sandbox 代码沙盒

@jamfie, you are using different useForm for each component. @jamfie,您为每个组件使用不同的useForm

Your form need to have the same instance, you can do that by using useformcontext or by passing props to components.您的表单需要具有相同的实例,您可以通过使用useformcontext或将 props 传递给组件来实现。

Also, you do not need Controller for this thing, here is codesandbox shows how you can use reactstrap with react-hook-form.此外,你不需要控制器来做这件事,这里是代码和框展示了如何使用 reactstrap 和 react-hook-form。

You can also follow this answer in github issue.您也可以在 github 问题中关注此答案

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

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