【发布时间】:2021-05-09 14:45:15
【问题描述】:
我正在尝试将 ref 从父组件(EditableCell)传递给子组件(输入),并在单击父组件时使用其.current.focus 属性。
我正在使用打字稿的forwardRef 函数,但我无法正确输入它
interface Props {
// Some props type
}
const CellEditable = (props: Props) => {
const [isEditing, setEditing] = useState<boolean>(false)
const inputRef = useRef<HTMLInputElement>(null)
const handleClick = () => setEditing(!isEditing)
const opts = {
ref: inputRef,
value: props.value,
onChange: props.onChange
}
return (
<div onClick={handleClick}>
{
isEditing
? <InputText {...opts} />
: <div>{props.value}</div>
}
</div>
)
}
interface Props {
// Some props type
}
type Ref = HTMLInputElement
const InputText = forwardRef((props: Props, ref: Ref) => {
useEffect(() => {
ref?.current?.focus()
})
return (
<input
type='text'
ref={ref}
value={props.value}
onChange={props.onChange}
/>
)
})
使用上面的代码,我得到以下错误:
Argument of type '(props: Props, ref: Ref) => JSX.Element' is not assignable to parameter of type 'ForwardRefRenderFunction<unknown, Props>'.
Types of parameters 'ref' and 'ref' are incompatible.
Type '((instance: unknown) => void) | MutableRefObject<unknown> | null' is not assignable to type 'HTMLInputElement'.
Type 'null' is not assignable to type 'HTMLInputElement'. TS2345
如果我用泛型输入forwardRed,我会得到另一种错误:
const InputText = forwardRef<Ref, Props>((props, ref) => { ... }
Property 'current' does not exist on type '((instance: HTMLInputElement | null) => void) | MutableRefObject<HTMLInputElement | null>'.
Property 'current' does not exist on type '(instance: HTMLInputElement | null) => void'. TS2339
最后,将 ref 输入为 any 不会出错。
我是 Typescript 新手,不明白上面提到的错误。
【问题讨论】:
-
forwardRef<HTMLInputElement, Props>((props, ref) => {})- 你能试试这个吗? -
我收到第二个错误:
Property 'current' does not exist on type '((instance: HTMLInputElement | null) => void) | MutableRefObject<HTMLInputElement | null>'. -
这个问题解决了吗?
标签: reactjs typescript ref