javascript - React-hook-form v7 - 自定义输入警告函数组件无法给出引用

标签 javascript reactjs react-hook-form react-ref

我正在将 React-Hook-Form 从 v6 迁移到 v7,但我的自定义输入遇到了一些问题。

这是第一次调用自定义输入时控制台的警告: enter image description here

这是我的父级代码(表单):

 <form onSubmit={handleSubmit(onSubmit)}>
    <div className="row">
        <div className="md-8">
            <div className="form-group">
                  <Input
                     name="host"
                     label="Adresse host *"
                     error={errors.host}
                     {...register('host')}
                  />
             </div>
        </div> 
    </div>
</form>

这里是 child 的代码:

import React from 'react'

type Props = {
    name?:string
    label?: string
    error?: any
    type?: string
    placeholder?: string
    helper?:string
}

const Input: React.FC<Props> = (props) => {

    const {name, label, error, type, placeholder, helper, ...rest} = props

    return(
        <div className="form-group inputText">
            {label && <label htmlFor={name}>{label}</label>}
            <input 
                type={type ?? "text"} 
                name={name}
                placeholder={placeholder ?? ""}
                className={`form-input ${error ? "form-error" : ''}`}
                {...rest}/>
            {!!helper && <small className="input-helper">{helper}</small>}
            {error && <span className="input-error red" style={{marginBottom: 5}}>{error.type === "required" ? "Champs obligatoire" : error.message}</span>}
        </div>
    )
}

export default Input

该表格有效,但错误困扰着我。尽管我在互联网上搜索无果,但我无法删除它......

非常感谢!

最佳答案

好吧,我不知道为什么我第一次没有成功,但是通过向我的组件添加一个forwardRef,问题就消失了...... 像这样:

const Input: React.FC<Props> = React.forwardRef((props, ref) => {
   [...]
    <input 
       type={type ?? "text"} 
       name={name}
       placeholder={placeholder ?? ""}
       ref={ref}
       className={`form-input ${error ? "form-error" : ''}`}
       {...rest}/>
   [...]
})

关于javascript - React-hook-form v7 - 自定义输入警告函数组件无法给出引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68266752/

相关文章:

javascript - 是否可以在不重新部署的情况下更新 PhoneGap 应用程序中的 HTML/CSS/JS 文件?

javascript - React - 未捕获的类型错误 : Cannot read property 'state' of > null

javascript - TSLint `import-name` 提示 import React from 'react' 并将其变为小写

reactjs - `react-hook-form` 在空输入时显示错误消息

javascript - 将单击事件附加到尚未添加到 DOM 的 JQuery 对象

JavaScript - 使用对象原型(prototype)来扩展方法的使用?

javascript - 当 http get 请求状态返回 404 时显示 Angular Material mat-error

reactjs - React-Redux 和 Connect - 为什么我的状态在点击时没有更新?

javascript - React Hook Form 将复选框设置为选中状态

reactjs - React Hook Forms 如何使用 Typescript 将错误作为 Prop 传递