简体   繁体   English

如何从 object 渲染动态 React 组件

[英]How to render dynamic React component from object

Need to render an imported component, like below, with some props inside my React code.需要渲染一个导入的组件,如下所示,在我的 React 代码中包含一些道具。 I'm thinking this is simple, but I can't find an answer on Stack overflow for this a format like this.我认为这很简单,但我无法在 Stack overflow 上找到这种格式的答案。 How would this be done?这将如何完成? Thank you.谢谢你。

import { HomeIcon } from "../lib/icons";

[{
    title: "Home",
    icon: ({ color }: { color: string }) => <HomeIcon color={color} />,
}].map((item, index) => {
        
   const { title, icon: Icon } = item;

   return (
       <div>
           <Icon color="#fff" /> // Doesn't work!
       </div>
   )

EDIT: Here is the error when running the code below编辑:这是运行以下代码时的错误在此处输入图像描述

OP: Got it, it was a type issue. OP:明白了,这是一个类型问题。 'any' isn't accepted here, we have to define icon like this这里不接受'any',我们必须这样定义图标

          icon: (({ color }: { color: string }) => (
            <HomeIcon color={color} />
          )) as React.ElementType<{ color: string }>,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM