[英]Material-UI: How to declare a type for React.ComponentType<P> with typescript
我正在使用 Typescript 和Material-UI我想為這樣的變量聲明組件類型
import MoreVert from '@material-ui/icons/MoreVert'
import { SvgIconProps } from '@material-ui/core/SvgIcon';
let myIcon: SvgIconProps = <MoreVert />; // does not work
但我收到錯誤:
[ts]
Type 'Element' is not assignable to type 'SvgIconProps'.
Types of property 'type' are incompatible.
Type 'string | ComponentClass<any> | StatelessComponent<any>' is not assignable to type 'string'.
Type 'ComponentClass<any>' is not assignable to type 'string'.
這就是 SvgIcon.ts 的樣子。 我究竟做錯了什么?
import * as React from 'react';
import { StandardProps, PropTypes } from '..';
export interface SvgIconProps
extends StandardProps<React.SVGProps<SVGSVGElement>, SvgIconClassKey> {
color?: PropTypes.Color | 'action' | 'disabled' | 'error';
component?: React.ReactType<SvgIconProps>;
fontSize?: 'inherit' | 'default' | 'small' | 'large';
nativeColor?: string;
titleAccess?: string;
viewBox?: string;
}
export type SvgIconClassKey =
| 'root'
| 'colorSecondary'
| 'colorAction'
| 'colorDisabled'
| 'colorError'
| 'colorPrimary'
| 'fontSizeInherit'
| 'fontSizeSmall'
| 'fontSizeLarge';
declare const SvgIcon: React.ComponentType<SvgIconProps>;
export default SvgIcon;
參考: https : //www.typescriptlang.org/docs/handbook/jsx.html
默認情況下,JSX 表達式的結果類型為 any。 您可以通過指定 JSX.Element 接口來自定義類型。 但是,無法從此接口檢索有關 JSX 的元素、屬性或子項的類型信息。 它是一個黑匣子。
我使用JSX.Element
丟失所有類型信息的JSX.Element
是因為它擴展了React.ReactElement<any>
,它的類型為any
。 為了解決這個問題,我像這樣使用它
let myIcon: React.ReactElement<SvgIconProps> = <MoreVert />;
現在我有了包含所有類型信息的元素。
正如 Ebuall 在評論中已經簡要描述的那樣,以下是根據您想要 JSX 元素還是組件類型來聲明變量的方式:
let myIconElement: JSX.Element = <MoreVert />;
let MyIconComponent: React.ComponentType<SvgIconProps> = MoreVert;
// Example component that uses the icon
function myComponent(props: {}) {
return <>
{myIconElement}
{<MyIconComponent />}
</>;
}
如果有人不通過回答@Murat Karagöz 的問題的方式工作,您可以在使用TypeScript從Material UI初始化界面或圖標的變量時嘗試這個。
我通過這樣聲明來完成這項工作:
import ShowChartIconOutlined from '@material-ui/icons/ShowChartOutlined'; import { SvgIconProps } from '@material-ui/core'; type Menu = { id: number; icon: (props: SvgIconProps) => JSX.Element; label: string; }[]; const NavBarMenus: Menu = [ { id: 1, icon: ShowChartIconOutlined, label: 'Dashboard', }, ... ];
參考: [Docs & Types] 在 TypeScript 中從 @material-ui/icons 導入圖標 #647
<MoreVert />
是一個組件。
SvgIconProps
只是定義傳遞給這個組件的 props 列表。
你應該試試:
let myIcon: SvgIcon = <MoreVert />;
我發現所有這些答案對我沒有幫助。
因此,最簡單的解決方法是使用any
類型聲明:
let myIcon: any = MoreVert;
而不是將其用作組件:
<myIcon />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.