[英]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.