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

React类组件中如何获取react-router 6的路由参数?

React Router 6 类组件获取路由参数解决方案

因为React Router 6已移除RouteComponentProps和withRouter,且类组件无法直接使用useParams钩子,以下是两种可行的解决方案:

方案一:函数组件作为中间层(推荐,实现简单)

用一个函数组件作为路由的element,在其中通过useParams获取参数,再传递给类组件。

  1. 路由配置修改:
<Route path="/modify/:id" element={<ModifyWrapper />} />
  1. 创建中间层组件ModifyWrapper:
import { useParams } from 'react-router-dom';
import Modify from './Modify';

// 定义params类型,确保id为string类型
const ModifyWrapper = () => {
  const { id } = useParams<{ id: string }>();
  // 将id作为props传给类组件
  return <Modify id={id!} />;
};

export default ModifyWrapper;
  1. 类组件Modify接收props:
import React from 'react';

// 定义组件props类型
type ModifyProps = {
  id: string;
};

class Modify extends React.Component<ModifyProps> {
  render() {
    return <div>当前修改的ID:{this.props.id}</div>;
  }
}

export default Modify;

方案二:自定义withRouter高阶组件

如果你的项目中有多个类组件需要路由相关数据,可以封装一个自定义的withRouter,模拟React Router 5的功能。

  1. 封装withRouter:
import { useParams, useLocation, useNavigate, type Params, type Location, type NavigateFunction } from 'react-router-dom';
import React from 'react';

// 定义注入的路由相关props类型
type WithRouterInjectedProps = {
  params: Params<string>;
  location: Location;
  navigate: NavigateFunction;
};

// 高阶组件:给类组件注入路由数据
function withRouter<P extends object>(Component: React.ComponentType<P & WithRouterInjectedProps>) {
  return function WrappedComponent(props: P) {
    const params = useParams();
    const location = useLocation();
    const navigate = useNavigate();
    return <Component {...props} params={params} location={location} navigate={navigate} />;
  };
}

export default withRouter;
  1. 类组件使用withRouter:
import React from 'react';
import withRouter from './withRouter';

// 定义组件props,包含注入的params
type ModifyProps = {
  params: { id: string };
};

class Modify extends React.Component<ModifyProps> {
  render() {
    return <div>当前修改的ID:{this.props.params.id}</div>;
  }
}

// 用withRouter包裹组件
export default withRouter(Modify);
  1. 路由配置无需额外中间层:
<Route path="/modify/:id" element={<Modify />} />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 02:52:19