gpt4 book ai didi

reactjs - Typescript RefForwardingComponent 不起作用

转载 作者:行者123 更新时间:2023-12-03 14:02:31 25 4
gpt4 key购买 nike

我正在尝试让我的组件接受引用。

我有一个像这样的组件:

const MyComponent: RefForwardingComponent<HTMLDivElement, IMyComponentProps> = (props, ref) => {
return <div ref={ref}>Hoopla</div>
}

但是当我尝试将引用传递给时,就像这样:

<MyComponent ref={myRef}></MyComponent>

...我收到此错误:

Property 'ref' does not exist on type 'IntrinsicAttributes & IMyComponentProps & { children?: ReactNode; }'.ts(2322)

我做错了什么?

最佳答案

RefForwardingComponentrender function ,它接收 props 和 ref 参数并返回一个 React 节点 - 它是没有组件:

The second ref argument only exists when you define a component with React.forwardRef call. Regular function or class components don’t receive the ref argument, and ref is not available in props either. (docs)

这也是 RefForwardingComponentdeprecated 的原因。支持 ForwardRefRenderFunction,它在功能上是等效的,但具有不同的名称以使区别更清晰。

您使用 React.forwardRef将渲染函数转换为接受引用的实际组件:

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

关于reactjs - Typescript RefForwardingComponent 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58991706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com