Typescript RefForwardingComponent not working

时光毁灭记忆、已成空白 提交于 2020-02-24 10:07:11

问题


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

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)

What am I doing wrong?


回答1:


Your code is right but you are missing a small detail.

When you use RefForwardingComponent you need to export the component wrapped with forwardRef

import React, { forwardRef, RefForwardingComponent } from 'react';

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

export default forwardRef(MyComponent);




回答2:


I think this is a bug in React's type definitions for RefForwardingComponent. You can work around this by adding the ref?: React.RefObject<HTMLDivElement> to your props. This will fix your compiler error.

try this:

type IMyComponentProps = {
    ref?: React.RefObject<HTMLDivElement>
}

I believe this requirement is a bug, because it should be added to the props for you by RefForwardingComponent. Putting it in your own props means that TypeScript will expect the props argument inside your function to contain the ref prop and I don't think it does. This however is not a big problem.




回答3:


Custom function components can't have 'ref' as a prop. You will have to give it a different name. 'yourRef', for example will be inside the props object.

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

So to use the ref prop:

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

or you can descructure the props:

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


来源:https://stackoverflow.com/questions/58991706/typescript-refforwardingcomponent-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!