Material-UI:如何使用打字稿为 React.ComponentType<P> 声明类型

新手上路,请多包涵

我正在使用 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;

原文由 Murat Karagöz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 315
2 个回答

参考: https ://www.typescriptlang.org/docs/handbook/jsx.html

默认情况下,JSX 表达式的结果类型为 any。您可以通过指定 JSX.Element 接口来自定义类型。但是,无法从此接口检索有关元素、属性或 JSX 子元素的类型信息。这是一个黑盒子。

我丢失所有类型信息的原因 JSX.Element 是因为它扩展了 React.ReactElement<any> 类型为 any 。为了解决这个问题,我像这样使用它

 let myIcon: React.ReactElement<SvgIconProps> = <MoreVert />;

现在我有了包含所有类型信息的元素。

原文由 Murat Karagöz 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果有人不按 @Murat Karagöz 的回答问题的方式工作,您可以在使用 TypeScriptMaterial 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',
  },
...
];

_参考: [[文档和类型] 在 TypeScript 中从 @material-ui/icons 导入图标 #647_](https://stackoverflow.com/questions/52537285/material-ui-how-to-declare-a-type-for-react-componenttypep-with-typescript)

原文由 Sauer Voussoir 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题