React类组件中如何获取react-router 6的路由参数?
React Router 6 类组件获取路由参数解决方案
因为React Router 6已移除RouteComponentProps和withRouter,且类组件无法直接使用useParams钩子,以下是两种可行的解决方案:
方案一:函数组件作为中间层(推荐,实现简单)
用一个函数组件作为路由的element,在其中通过useParams获取参数,再传递给类组件。
- 路由配置修改:
<Route path="/modify/:id" element={<ModifyWrapper />} />
- 创建中间层组件
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;
- 类组件
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的功能。
- 封装
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;
- 类组件使用
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);
- 路由配置无需额外中间层:
<Route path="/modify/:id" element={<Modify />} />
内容的提问来源于stack exchange,提问作者Enricosoft
相关产品推荐
相关产品推荐

