我有这个侧边栏数据

export const adminSidebarData: SidebarProps["sidebarData"] = [
  {
    title: "Dashboard",
    link: "/admin/dashboard",
    IconComponent: <IconDashboard className="icon" />,
  },
  {
    title: "Users",
    link: "/admin/dashboard/users",
    IconComponent: <IconDashboard />,
  }
];

sidebarData的Typescript 类型是

sidebarData: {
    title: string;
    link: string;
    IconComponent: JSX.Element;
  }[];

我在用户界面中呈现数据,如下所示:

{sidebarData.map((data) => {
          return (
            <Link href={data.link} className="w-full" key={data.link}>
              <div
                key={data.link}
                className="mx-2 flex w-full bg-white px-2 py-2"
              >
                {data.IconComponent}
                <p className="">{data.title}</p>
              </div>
            </Link>
          );
        })}

如你所见,我呈现的图标是{data.IconComponent},我不能以这种方式将动态props 传递给组件

But I wanted to render the component as <data.IconComponent/> or <IconComponent/> so that I will be able to pass props dynamically. Maybe changing the color based on the current route.
What change should I make to achieve this? Thank you.

推荐答案

你可以这样做

type SidebarItem = {
  title: string;
  link: string;
  IconComponent: React.ComponentType<{ className?: string }>;
};
type SidebarProps = {
  sidebarData: SidebarItem[];
};

Reactjs相关问答推荐

从app.js导航,这是在BrowserRouter包装之外

使用Reaction-Hook-Form时未激发React.js onBlur事件

同一文件中前端和后端的Nginx配置

React Context未正确更新

当项目开始时,它不会从三元运算符(REACT)加载一些tailwind 类名称

阻止组件更新的多分派Redux Thunk或setState是否有任何问题

如何使用react-router-dom保护嵌套在受保护路由中的嵌套路由?

如果我使用 formik,如何在嵌套对象中写入正确的值?

如何管理组件列表的复杂状态? (Nextjs/ReactJS)

我发送的 prop 的值不会改变.如果成功登录,导航栏中的 prop 必须为 true.我从后端得到 200 ok

Redux 工具包不更新状态

如何在我的自定义主题中样式化MUI TreeItem组件

有没有办法在用户离开页面时防止输入模糊?

我应该如何将字符串作为props 传递给 React 组件?

为什么接受 useState 返回的函数的 setter 在使用 React 的单个调用中执行两次?

不能在我的代码中使用 .给我一个警告!有人知道解决方案吗?

如何使用react 路由将 url 参数限制为一组特定的值?

如何在 React 中单击鼠标的位置动态添加 div?

如果查询不存在,如何返回所有产品?

当父组件重新渲染时做出react ,我失go 了子状态.我错过了什么?