打字稿RefForwardingComponent无法正常工作 [英] Typescript RefForwardingComponent not working

查看:467
本文介绍了打字稿RefForwardingComponent无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使我的组件接受引用.

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)

我在做什么错了?

推荐答案

RefForwardingComponent

仅当您使用React.forwardRef调用定义组件时,第二个ref参数才存在.常规函数或类组件不会接收ref参数,并且ref在props中也不可用. (文档)

这也是原因,为什么RefForwardingComponent 已弃用,而支持ForwardRefRenderFunction,它在功能上是等效的,但名称不同,使区分更加清晰.

That is also the reason, why RefForwardingComponent is deprecated in favor of ForwardRefRenderFunction, which is functionally equivalent, but has a different name to make the distinction clearer.

您使用 React.forwardRef 将render函数变成接受参考的实际组件:

You use 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} />

这篇关于打字稿RefForwardingComponent无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆