React Router 5中如何给路由配置项内的组件变量传递自定义Props
解决方法
你原本已经知道用Route的render属性传参的写法,这个场景下只需要把动态组件从配置项取出后正常实例化即可,具体修改如下:
- 修改
App.tsx中路由渲染逻辑,将原component属性替换为render属性实现自定义传参:
{routes.map((route: RouteItem) => ( <Route key={route.key} path={route.path} exact render={(routerProps) => { // 取出配置中的组件,注意JSX要求自定义组件首字母必须大写 const RenderComponent = route.component || DefaultComponent; // 同时传递路由原生props(history/location/match等) + 自定义业务参数 return ( <RenderComponent {...routerProps} title={route.title} contentPath={route.contentPath} // 其他需要传递的RouteItem字段可直接在此处追加 /> ); }} /> ))}
- (可选,解决TS类型报错)调整
RouteItem接口中component的类型定义,声明组件可接收的参数类型:
import { FC, ComponentType } from "react"; import { RouteComponentProps } from "react-router-dom"; // 定义路由组件可接收的自定义参数类型 interface CustomRouteProps { title?: string; contentPath?: string; } interface RouteItem { key: string; title: string; tooltip?: string; path?: string; // 合并路由原生props和自定义props类型 component?: FC<RouteComponentProps & CustomRouteProps>; contentPath?: string; enabled: boolean; icon?: ComponentType; subRoutes?: Array<RouteItem>; appendDivider?: boolean; }
内容的提问来源于stack exchange,提问作者brandonscript
相关产品推荐
相关产品推荐

