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

如何将表格单元格内带参数的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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 09:30:05