【问题标题】:react-hooks-form conflict with reactstrapreact-hooks-form 与 reactstrap 冲突
【发布时间】:2023-03-21 21:21:02
【问题描述】:

我正在尝试将react-hook-form 添加到我的reactstrap 表单和输入中,但看起来包之间存在冲突。

import React, { useState, useEffect } from 'react';
import { useForm } from "react-hook-form";
import {
    Button,
    Form,
    Label,
    Input
} from 'reactstrap';
import { FormControlLabel, Checkbox, FormGroup } from '@material-ui/core';

...

const { register, handleSubmit, errors } = useForm();

...

const updDetails = (data) => {
   console.log(data);    
}

return (
   <Form onSubmit={handleSubmit(updDetails)}>
      <FormGroup className="mr-10 mb-10">
         <Label for="compName" className="mr-sm-10">Company Name</Label>
         <Input type="text" name="compName" id="compName" placeholder="Company Name"
            ref={register({ required: true })} aria-invalid={errors.name ? "true" : "false"}
            value={compDetails.compName} onChange={(e) => setCompDetails({...compDetails, compName: e.target.value})}
         />
         {errors.name && errors.name.type === "required" && (
            <span role="alert">This is required</span>
         )} 
      </FormGroup>
      <Button type="submit" className="col-sm-3" color="primary">Update Details</Button>
   </Form>
)
...

当我加载页面时,我可以在浏览器控制台中看到我所有输入的警告:Field is missing `name` attribute 。但是,我在上面的代码中将名称添加到每个输入中。此外,当我单击Update Details 时,compName 的值为空,它提交并且数据为空对象。 我不能将react-hook-form 与reactstrap 一起使用吗?

谢谢

【问题讨论】:

  • 不确定这些事情是否是问题的原因,但以下事情看起来不对:您不需要Input 上的value 和onChange。如果需要该值,可以从useForm 解构values。 errors.name 应该是 errors.compName。同样重要的是,reactstrap 转发裁判。我不确定,如果它这样做......

标签: reactjs reactstrap react-hook-form


【解决方案1】:

您可能必须在Input 组件上使用innerRef 而不是ref。我在源代码here 中找到了这个。

<Input
  type="text"
  name="compName"
  id="compName"
  placeholder="Company Name"
  innerRef={register({ required: true })}
  aria-invalid={errors.compName ? "true" : "false"}
/>

【讨论】:

  • 谢谢。这就是问题所在。如果出现错误,如何将输入边框设置为红色?
  • 可能使用类似于aria-invalid 的无效属性(如果errors.compName 不为空/未定义,则设置为true)。文档和源代码可能会有所帮助。
【解决方案2】:

我不熟悉reactstrap 代码,但是您可以做的是将名称传递给注册函数,这样使用它:

ref={register({name: 'input-name', /* rest of options*/})}

希望我能帮上忙:D

【讨论】:

    猜你喜欢
    • 2018-10-23
    • 2022-11-22
    • 2020-04-04
    • 2020-01-11
    • 2021-09-23
    • 2019-11-08
    • 2020-10-23
    • 1970-01-01
    • 2016-08-29
    相关资源
    最近更新 更多