所以,我想这样创建路由:
<Routes>
{
SidebarItems.map(el =>
<Route key={el.text} path={el.link} element={<el.text/>}/>
)
}
</Routes>
SidebarItems
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)}/>
)
}