在React with Typescript中为RefObject使用可赋值类型



我正在使用带有Typescript和Material UI的React。我想通过一个裁判作为道具。在小工具对话框中,我有

export interface WidgetDialogProps {
....
ref?: React.RefObject<HTMLDivElement>;
}
....
<div data-id={dataId} className={classes.dialog} ref={ref}>
--- dialog content ---          
</div>

当我想在其他组件中使用它时:

const canvasRef = React.useRef<HTMLDivElement>(null);
<WidgetDialog
ref={canvasRef}
....
>
....
</WidgetDialog>

我得到这种类型的错误:

Type 'RefObject<HTMLDivElement>' is not assignable to type '(string & RefObject<HTMLDivElement>) | (((instance: Component<WidgetDialogProps, any, any> | null) => void) & RefObject<...>) | (RefObject<...> & RefObject<...>) | undefined'.
Type 'RefObject<HTMLDivElement>' is not assignable to type 'RefObject<Component<WidgetDialogProps, any, any>> & RefObject<HTMLDivElement>'.
Type 'RefObject<HTMLDivElement>' is not assignable to type 'RefObject<Component<WidgetDialogProps, any, any>>'.
Type 'HTMLDivElement' is missing the following properties from type 'Component<WidgetDialogProps, any, any>': context, setState, forceUpdate, render, and 3 more.ts(2322)
index.d.ts(107, 9): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<Component<WidgetDialogProps, any, any>> & Readonly<...> & Readonly<...>'

接口中ref的正确类型是什么?

我认为ref是一个保留属性,发生错误是因为WidgetDialog试图使用它。尝试将属性名称更改为其他名称,例如:

export interface WidgetDialogProps {
....
rif?: React.RefObject<HTMLDivElement>;
}
....
<div data-id={dataId} className={classes.dialog} ref={rif}>
--- dialog content ---          
</div>
const canvasRef = React.useRef<HTMLDivElement>(null);
<WidgetDialog
rif={canvasRef}
....
>
....
</WidgetDialog>

另请参阅:https://alligator.io/react/createref/

最新更新