【问题标题】:Export a list of objects in typescript, and dynamically import them a react component在 typescript 中导出对象列表,并将它们动态导入一个反应组件
【发布时间】:2021-06-11 11:48:53
【问题描述】:

我有一个对象,在 tsx 文件中包含名称/组件的键/值对。

//icons.tsx

import { BirdIcon, CatIcon } from 'components/Icons';

interface Map {
  [key: string]: string | undefined;
}

export const Icons: Map = {
  birds: <BirdIcon />,
  cats: <CatIcon />,
};

我在说的对象中遇到错误

类型“元素”不可分配给类型“字符串”.ts(2322)

我正在尝试将其动态导入到我的 next.js 组件中,但出现以下错误

const DynamicComponent = dynamic(() =>
  import('./Icons/').then((mod) => mod.Icons),
);

我收到以下错误

    Type 'Map' is not assignable to type 'ComponentType<{}> | { default: ComponentType<{}>; }'.

这里有什么建议吗?

【问题讨论】:

  • next/dynamic 应该返回一个 React 组件,但 mod.Icons 是一个对象。

标签: reactjs typescript next.js


【解决方案1】:

将您的界面更改为:

interface Map {
  [key: string]: React.Component<{}> | undefined;
}

此外,您需要从地图中选择一个组件,因为它是动态的。

【讨论】:

  • 我现在在键上收到此错误>类型“元素”不可分配给类型“组件”.ts(2322)
猜你喜欢
  • 2021-11-10
  • 2014-08-22
  • 2019-06-03
  • 2018-04-28
  • 2021-03-06
  • 1970-01-01
  • 2021-09-01
  • 2021-11-09
  • 1970-01-01
相关资源
最近更新 更多