这是我的 react-hook - 控制器
<Controller
control={control}
name={name}
defaultValue={defaultValue}
rules={validate}
ref={register({
validate
})}
render={props => (
<input
name={props.name}
value={props.value}
ref={props.ref}
type={'text'}
placeholder={label}
aria-label={label}
onChange={handleChange}
data-error={errorText !== '' && errorText}
/>
)}
/>
问题是 ref 不起作用。它需要是 inputRef - 由 react-hook-form 示例确定。 如果我使用 inputRef,我会收到打字稿错误:
<块引用>属性 'inputRef' 不存在于类型 'DetailedHTMLProps
如果我尝试将该属性添加到 index.d.ts 文件,它会破坏我所有其他声明的模块..
declare module 'react' {
import React from 'react';
interface HTMLInputAttributes<T> extends React.HTMLAttributes<T> {
// extends React's HTMLAttributes
inputRef?: any;
}
}
declare module '*.svg' {
const content: any;
export const ReactComponent: any;
export default content;
}
答案 0 :(得分:1)
我已经把 ref 放在了控制器上,而它应该放在输入本身中。 修复:
<Controller
control={control}
name={name}
render={props => (
<input
name={props.name}
defaultValue={defaultValue}
ref={register({
validate
})}
type={'text'}
placeholder={label}
aria-label={label}
onChange={handleChange}
data-error={errorText !== '' && errorText}
/>
)}