[英]I can't type the ref correctly using useRef hook in typescript
I'm trying to pass a ref from a parent component (an EditableCell) to a Child component (Input) and use its .current.focus
property when the parent is clicked.我正在尝试将 ref 从父组件(EditableCell)传递给子组件(Input),并在单击父组件时使用其
.current.focus
属性。
I'm using the forwardRef
function using typescript but I have trouble typing it correctly我正在使用
forwardRef
function 使用 typescript 但我无法正确输入
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}
/>
)
})
With the code above, I get the following error:使用上面的代码,我收到以下错误:
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
If I type the forwardRed
with generics, I get a different kind of error:如果我用 generics 键入
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
Finally, typing the ref as any
give me no error.最后,将 ref 输入为
any
给我任何错误。
I am new to Typescript and I don't understand the error mentioned above.我是 Typescript 的新手,我不明白上面提到的错误。
Check out following sandbox: https://codesandbox.io/s/aged-night-3pwjs .查看以下沙箱: https://codesandbox.io/s/aged-night-3pwjs 。
TypeScript warns you that your ref could be possibly null, therefore any code with ref.current
should be wrapped with if statement, which will ensure that ref.current
exists. TypeScript 警告您,您的 ref 可能是 null,因此任何带有
ref.current
的代码都应该用 if 语句包装,这将确保ref.current
存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.