繁体   English   中英

如何在 React-router-dom 和 React 中动态渲染 Route 组件

[英]How to dynamically render Route components in React-router-dom and React

所以,我想以这种方式创建路线:

<Routes>
  {
    SidebarItems.map(el => 
      <Route key={el.text} path={el.link} element={<el.text/>}/>
    )
  }
</Routes>

侧边栏项目

export const SidebarItems: Array<SidebarItem> = [
    {
        text: "Educatie",
        icon: SchoolIcon,
        link: '/educatie'
    },
    {
        text: "Experienta",
        icon: DoneIcon,
        link: '/experienta'
    },
    {
        text: "Judete",
        icon: MapIcon,
        link: '/judete'
    },
    {
        text: "Localitati",
        icon: MapsHomeWorkIcon,
        link: '/localitati'
    },
    {
        text: "Tipuri de contract",
        icon: ArticleIcon,
        link: '/tipuricontract'
    }
];

组件具有来自 text 属性的名称。 我观察到,如果我明确调用一个组件,例如:

<Route path="/" element={<Educatie/>}/>

它会起作用的。 但是只使用文本是行不通的——我需要引用组件本身。

在我的具体情况下,我该怎么做?

我会做这样的事情:

 const Component1 = React.lazy(() => import ('./Component1')); const Component2 = React.lazy(() => import ('./Component2')); const componentHandler = (text) => { switch text { case 'component 1': return <Component1 / > ; case 'component 2': return <Component2 / > default: null } } ////////// { SidebarItems.map(el => <Route key = {el.text} path = {el.link} element={componentHandler(el.text)}/> ) }

暂无
暂无

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

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