动态路由:React/TypeScript



我正在将React/JavaScript项目转换为React/TypeScript。我正在使用react-router-dom来处理所有的路由问题。所以,我有一个名为routes/index.js的文件(是的,一个JavaScript文件(,在这个文件中你会发现这样的东西:

import { lazy } from 'react'
// use lazy for better code splitting, a.k.a. load faster
const Dashboard = lazy(() => import('../pages/Dashboard'))
const routes = [
{
path: '/dashboard', // the url
component: Dashboard, // view rendered
},
]
export default routes

在另一个帮助我加载路由的文件中,我有以下代码:

<Switch>
{routes.map((route, i) => {
return route.component ? (
<Route
key={i}
exact={true}
path={`/app${route.path}`}
render={(props) => <route.component {...props} />}
/>
) : null;
})}
<Redirect exact from="/app" to="/app/dashboard" />
<Route component={Page404} />
</Switch>;

问题是<route.component {...props}/>,TypeScript给我这个错误:

键入"{history:history;location:location;match:match<{}>";;staticContext?:StaticContext |未定义;}'没有与类型"IntrnsicAttributes"共有的属性。

如何解决此问题?

据我所知,由于使用了小写的组件名称,您会出现此错误。所以,你可以使用这样的东西:

const Component = route.component as React.ComponentType;
...
return <Component {...someProps} />

您还可以为这个React.ComponentType提供一些通用类型