[英]Dynamic Routes: 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 给我这个错误:
键入'{历史:历史; 位置:位置; 匹配:匹配<{}>; 静态上下文?:静态上下文 | 不明确的; }' 与类型 'IntrinsicAttributes' 没有共同的属性。
我该如何解决这个问题?
据我所知,由于使用了小写的组件名称,您会收到此错误。 所以,你可以使用这样的东西:
const Component = route.component as React.ComponentType;
...
return <Component {...someProps} />
您还可以为此React.ComponentType
提供一些泛型类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.