如何在react-router-dom的Link组件中传递参数(无需onClick)?
当然可以!完全不用依赖onClick事件,React Router的<Link>组件本身就支持直接传递参数,主要有两种常用方式,根据你的需求选就行:
1. 路径参数(显式在URL中)
如果希望参数能出现在URL里(比如方便分享、刷新页面不丢失),可以用路径参数的方式:
步骤:
- 先在路由配置里定义参数占位符:
// React Router v5 写法 <Route path="/user/:userId" component={UserDetail} /> // React Router v6 写法 <Route path="/user/:userId" element={<UserDetail />} />
- 然后在
<Link>里动态拼接路径:
// 类组件场景 <Link to={`/user/${this.props.userId}`}>查看用户详情</Link> // 函数组件场景 <Link to={`/user/${userId}`}>查看用户详情</Link>
- 目标组件里获取参数:
// React Router v5 类组件 this.props.match.params.userId // React Router v6 函数组件 import { useParams } from 'react-router-dom'; const { userId } = useParams();
2. State隐式参数(不在URL中显示)
如果不想把参数暴露在URL里,只是组件间临时传递数据,直接给<Link>的to属性传一个对象就行,和你用router.push的逻辑几乎一致:
写法:
// 类组件场景 <Link to={{ pathname: '/user', state: { userId: this.props.userId } }} > 查看用户详情 </Link> // 函数组件场景 <Link to={{ pathname: '/user', state: { userId } }} > 查看用户详情 </Link>
- 目标组件里获取state:
// React Router v5 类组件 this.props.location.state.userId // React Router v6 函数组件 import { useLocation } from 'react-router-dom'; const location = useLocation(); const userId = location.state?.userId; // 用可选链避免state为空时报错
注意:这种方式的state存在内存中,刷新页面后会丢失,如果需要持久化数据,建议优先选择路径参数或者URL查询参数。
为什么推荐直接用Link而非onClick?
这种声明式写法更贴合React Router的设计理念,不需要手动绑定事件,代码更简洁易读,还能避免手动调用router.push可能出现的事件冒泡、重复跳转等问题。
内容的提问来源于stack exchange,提问作者Sam Fisher
相关产品推荐
相关产品推荐

