通过父组件的属性传递的 React 渲染字符串插值组件

React render string interpolated component passed via attribute of parent component

我正在尝试根据对象值数组呈现一个函数。 React 呈现为字符串而不是组件。所需的组件渲染是一个导入的图标。我已经尝试了在与 react-jsx-parse 等相关的其他问题中找到的各种解决方案。这些解决方案都不适用于这种情况。

import {
  LinkedIn,
  GitHub,
  Instagram,
  Camera,
  Favorite,
  Palette,
  Motorcycle,
} from "@mui/icons-material"; 
import myJsonInfo from "./myJsonInfo";
import AppBar from "@mui/material/AppBar";
import Tabs from "@mui/material/Tabs";
import Tab from "@mui/material/Tab";

function myPage(){

return (
...
               <AppBar position="static">
                  <Tabs
                    value={value}
                    onChange={handleChange}
                    indicatorColor="secondary"
                    textColor="inherit"
                    variant="fullWidth"
                    aria-label="full width tabs example"
                  >
                    {myJsonInfo.map((tab, id) => ( 
                      <Tab
                        label={tab.tabButton}
                        icon={`<${tab.tabIcon} sx={{ fontSize: 40 }} />`}
                        iconPosition="top"
                        key={id}
                      />
                    ))}
                  </Tabs>
                </AppBar>
...
)

我期待插值渲染...但实际渲染是...

...
icon={<Camera sx={{ fontSize: 40 }} />}    
icon={"<Camera sx={{ fontSize: 40 }} />"}
...

这是 json 对象...

export const myJsonInfo = [
  {
    tabButton: "PHOTOGRAPHY",
    tabIcon: "Camera",
    photos: [
      {
        src: "https://live.staticflickr.com/4894/45935502555_2f67f4525e_m.jpg",
        width: "240",
        height: "180",
        alt: "20190110_131623"
      },
      {
        src: "https://live.staticflickr.com/4413/36739958362_d6b357e792_m.jpg",
        width: "240",
        height: "86",
        alt: "_DSC1990-Pano"
      },
      {
        src: "https://live.staticflickr.com/849/39718694400_97c278f836_m.jpg",
        width: "240",
        height: "160",
        alt: "_DSC3436"
      },

      {
        src: "https://live.staticflickr.com/869/40528225894_2eac07c24e_m.jpg",
        width: "240",
        height: "180",
        alt: "GOPR0332"
      },
      {
        src: "https://live.staticflickr.com/1846/44291032431_9050d0e351_m.jpg",
        width: "240",
        height: "97",
        alt: "20180818_082245"
      },
      {
        src: "https://live.staticflickr.com/933/43285116024_690e779504_m.jpg",
        width: "240",
        height: "117",
        alt: "20180812_114422"
      }
    ]
  },
...

尝试这样的事情:

创建一个包含您的图标组件的对象:

import {
  LinkedIn,
  GitHub,
  Instagram,
  Camera,
  Favorite,
  Palette,
  Motorcycle,
} from "@mui/icons-material";
const iconComponents = { LinkedIn, GitHub /* ... */ };

如果要使用图标组件,请将其名称分配给局部变量:

{myJsonInfo.map((tab, id) => {
 const Icon = iconComponents[tab.tabIcon];
 return <Tab
   label={tab.tabButton}
   icon={<Icon sx={{ fontSize: 40 }} />}
   iconPosition="top"
   key={id}
 />
})}