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

如何定义RouteComponentProps类型以支持props传入额外自定义属性

解决方案

问题根因

RouteComponentProps 类型仅包含react-router-dom路由注入的match、location、history三类核心属性,你手动传入的user属于自定义属性,不在该类型的默认定义范围内,因此会触发属性不存在的类型报错。

方案1:类型交叉扩展(适配你当前使用的react-router-dom v5版本)

直接通过TS的交叉类型语法,把路由内置属性类型和你自定义的属性类型合并,作为最终的props类型:

import { RouteComponentProps } from 'react-router-dom';

// 此处User替换为你实际的user变量的类型,例如{id: string; name: string}
type CustomProps = {
  user: User;
}

// 交叉合并两种类型
const Restaurant = (props: RouteComponentProps<{id: string}> & CustomProps) => {
  const a = props.match.params.id;
  const b = props.user;
  // 其余业务逻辑
}

如果搭配React的FC泛型使用,写法如下:

import { FC } from 'react';
import { RouteComponentProps } from 'react-router-dom';

type RestaurantProps = RouteComponentProps<{id: string}> & {
  user: User;
}

const Restaurant: FC<RestaurantProps> = (props) => {
  // 业务逻辑
}

方案2:升级到react-router-dom v6后的简化写法

如果你后续升级到v6版本,可以用官方提供的路由钩子直接获取路由参数,不需要再继承RouteComponentProps,类型定义更简洁:

import { useParams } from 'react-router-dom';

// 仅需要定义自定义传入的属性即可
type RestaurantProps = {
  user: User;
}

const Restaurant = (props: RestaurantProps) => {
  // 直接通过钩子获取路由参数
  const { id } = useParams<{id: string}>();
  const { user } = props;
  // 其余业务逻辑
}

内容的提问来源于stack exchange,提问作者Loqz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 20:09:02