【发布时间】:2021-09-16 20:40:43
【问题描述】:
我正在将 React-Hook-Form 从 v6 迁移到 v7,我的自定义输入有一点问题。
这是我的父代码(表单):
<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>
这里是孩子的代码:
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
表单有效,但错误困扰着我。尽管我在互联网上搜索无果,但我无法删除它......
非常感谢!
【问题讨论】:
-
根据我的理解,您确定您的输入已正确注册,并且错误消息,来自
...register()的ref不会在没有@987654330 的情况下转发到您的Input组件@。可能值得在Input组件中注销您作为rest获得的内容?我的假设是它不会有ref -
你好@andymccullough,确实通过记录{...rest}我只有onChange和onBlur,没有参考。不知道是不是正常...其实我是按照React-hook-form的doc来的。
-
是的,因为
ref和key被视为不传递给孩子的特殊道具,为了将 ref 转发给孩子,您必须用forwardRef明确告诉它- reactjs.org/docs/forwarding-refs.html,正如您在回答中看到的那样
标签: javascript reactjs react-hook-form react-ref