如何将表格单元格内带参数的Link To替换为带参数的history.push
实现方案
该需求完全可以实现,根据你使用的react-router版本不同,对应实现方式如下:
前置条件
确保你的组件被Router组件包裹,否则路由相关hooks无法正常使用。
方案1:react-router v5 版本实现
- 第一步:在组件顶部引入useHistory hook
import { useHistory } from 'react-router-dom'
- 第二步:在组件函数顶层调用hook获取history实例,替换原有Link组件
const MyComponent = () => { const history = useHistory() // 保留你原有的其他逻辑,比如items的定义、其他状态等 return ( // 原有外层渲染逻辑 {items.map(item => ( <TableCell style={{width: '10%'}}> <span style={{ textDecoration: 'underline', color: 'black', cursor: 'pointer' }} onClick={() => history.push(`/run-id/${item.run_id}`)} > {item.run_id} </span> </TableCell> ))} ) }
方案2:react-router v6 版本实现
v6版本废弃了useHistory,替换为useNavigate,调整对应逻辑即可:
- 第一步:引入useNavigate hook
import { useNavigate } from 'react-router-dom'
- 第二步:调用hook获取navigate方法,修改点击事件逻辑
const MyComponent = () => { const navigate = useNavigate() // 保留你原有的其他逻辑 return ( // 原有外层渲染逻辑 {items.map(item => ( <TableCell style={{width: '10%'}}> <span style={{ textDecoration: 'underline', color: 'black', cursor: 'pointer' }} onClick={() => navigate(`/run-id/${item.run_id}`)} > {item.run_id} </span> </TableCell> ))} ) }
注意事项
- 给可点击元素添加
cursor: pointer样式,和原Link的交互体验保持一致 - 如果你需要保留
ctrl/cmd + 点击打开新标签页的特性,也可以换成a标签,阻止默认跳转后调用history.push/navigate方法即可
内容的提问来源于stack exchange,提问作者ArthurJ
相关产品推荐
相关产品推荐

