【问题标题】:Typescript Compilation Error with React - Type 'Element' is not assignable to type 'FunctionComponent<{}>'React 的 Typescript 编译错误 - 类型“元素”不可分配给类型“FunctionComponent<{}>”
【发布时间】:2020-07-04 06:26:10
【问题描述】:

使用的原始代码-

import { Create } from '@material-ui/icons';

<DroppableFolder
          count={draftsCount}
          sidebarOpen={open}
          folderId={FolderType.Drafts}
          Icon={Create}
          name="Drafts"
          type="folder"
          url={Communication.drafts}
/>

这是界面-

export default interface DroppableFolderProps {
  count?: number;
  folderId: string;
  label?: Label;
  Icon?: React.ComponentType;
  name?: string;
  type: LinkType;
  url: string;
  sidebarOpen?: boolean;
}

关于用这个 React 功能组件替换 Icon={Create}

const DraftIcon = <Icon icon="draft-icon" title="Draft Icon" size="medium" />;

<DroppableFolder
          count={draftsCount}
          sidebarOpen={open}
          folderId={FolderType.Drafts}
          Icon={DraftIcon}
          name="Drafts"
          type="folder"
          url={Communication.drafts}
/>

我收到此错误 -

type 'Element' is not assignable to type 'ComponentClass<{}, any> | FunctionComponent<{}> | undefined'.
  Type 'Element' is not assignable to type 'FunctionComponent<{}>'.
    Type 'Element' provides no match for the signature '(props: { children?: ReactNode; }, context?: any): ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<...>)> | null'.

对于Icon={DraftIcon}这一行。

有什么建议吗?

【问题讨论】:

    标签: reactjs typescript react-hooks


    【解决方案1】:

    试试这个,把 DroppableFolderProps 中的 Icon 属性改成 IconProps 类型

    interface DroppableFolderProps{
      Icon:IconProps
    }
    

    将 const DraftIcon 更改为函数式组件

    const DraftIcon = ()=> <Icon icon="draft-icon" title="Draft Icon" size="medium" />;
    

    并将 DraftIcon 传递给 DroppableFolderProps 组件

    <DroppableFolder Icon={ <DraftIcon/> } />
    

    【讨论】:

    • 将其更改为箭头函数有效 - const DraftIcon = ()=&gt; &lt;Icon icon="draft-icon" title="Draft Icon" size="medium" /&gt;; 但是,其余代码需要相同。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2020-11-09
    • 2019-12-01
    • 2022-08-23
    • 2019-12-30
    • 1970-01-01
    • 2020-03-12
    相关资源
    最近更新 更多