如何将react-hook-form v7与reactstrap 9一起使用?

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

我目前正在尝试使用react-hook-form v7和reactstrap 9创建一个表单,使用react 18。这是我当前的实现,但在我的控制台日志中,数据返回一个

undefined
。如果你们能告诉我如何正确整合它们,那将会很有帮助。 非常感谢!

  const { register, handleSubmit } = useForm();

  const onSubmit = (data) => {
    //here, the output is --> {email: undefined, password: undefined}
    console.log("sign in form data", data);
  };

// Sample Form
 <Form inline onSubmit={handleSubmit(onSubmit)}>
      <FormGroup className="mb-2">
        <Label className="auth-label" htmlFor="email">
          Email address*
        </Label>
        <Input
          id="email"
          name="email"
          placeholder=""
          type="email"
          className="auth-input"
          {...register("email")}
        />
      </FormGroup>
      <Button block className="auth-button mt-4">
        Login
      </Button>
 </Form>

reactjs react-hook-form reactstrap
2个回答
1
投票

尝试如下定义寄存器变量:

const { ref, ...sampleName } = register("name");

并在 Reactstrap 输入中使用此引用

<Input innerRef={ref} {...sampleName}/>

请在此处查看沙箱:https://codesandbox.io/s/reactstrap-sandbox-forked-z2uxl?file=/src/index.js:808-842


0
投票

改进@Eray的答案 您可以为所有输入创建一个原子组件

const { Input } = require("reactstrap");

const FormInput = ({ register, name, ...rest }) => {
  const { ref, ...registerField } = register(name);

  return <Input innerRef={ref} {...registerField} {...rest} />;
};

export default FormInput;

并像下面这样使用它:

  <FormGroup>
    <Label>Email</Label>
    <FormInput type="email" name="email" register={register} />
    <FormFeedback>{errors.email}</FormFeedback>
  </FormGroup>
© www.soinside.com 2019 - 2024. All rights reserved.