打字稿RefForwardingComponent无法正常工作 [英] Typescript RefForwardingComponent not working
问题描述
我正在尝试使我的组件接受引用.
I am trying to make my component accept a ref.
我有一个像这样的组件:
I have a component like so:
const MyComponent: RefForwardingComponent<HTMLDivElement, IMyComponentProps> = (props, ref) => {
return <div ref={ref}>Hoopla</div>
}
但是当我尝试将ref传递给它时,就像这样:
But when I try to pass a ref to is like so:
<MyComponent ref={myRef}></MyComponent>
...我收到此错误:
... I get this error:
Property 'ref' does not exist on type 'IntrinsicAttributes & IMyComponentProps & { children?: ReactNode; }'.ts(2322)
我在做什么错了?
推荐答案
仅当您使用React.forwardRef调用定义组件时,第二个ref参数才存在.常规函数或类组件不会接收ref参数,并且ref在props中也不可用. (文档)
这也是原因,为什么 That is also the reason, why 您使用 You use 这篇关于打字稿RefForwardingComponent无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!RefForwardingComponent
是
RefForwardingComponent
已弃用,而支持ForwardRefRenderFunction
,它在功能上是等效的,但名称不同,使区分更加清晰.RefForwardingComponent
is deprecated in favor of ForwardRefRenderFunction
, which is functionally equivalent, but has a different name to make the distinction clearer.React.forwardRef
将render函数变成接受参考的实际组件:React.forwardRef
to turn the render function into an actual component that accepts refs:import React, { ForwardRefRenderFunction } from 'react'
type IMyComponentProps = { a: string }
const MyComponentRenderFn: ForwardRefRenderFunction<HTMLDivElement, IMyComponentProps> =
(props, ref) => <div ref={ref}>Hoopla</div>
const MyComponent = React.forwardRef(MyComponentRenderFn);
const myRef = React.createRef<HTMLDivElement>();
<MyComponent a="foo" ref={myRef} />