You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Router 5中如何给路由配置项内的组件变量传递自定义Props

解决方法

你原本已经知道用Route的render属性传参的写法,这个场景下只需要把动态组件从配置项取出后正常实例化即可,具体修改如下:

  1. 修改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字段可直接在此处追加
        />
      );
    }}
  />
))}
  1. (可选,解决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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 00:06:03