如何在Material UI表格中使用react-router-dom的Link实现整行跳转并解决DOM层级报错
解决方案
报错是因为HTML表格有严格的嵌套规范,<tr>的直接子元素只能是<td>/<th>,<td>也不能作为<a>的直接子元素,你可以用以下两种常用方案实现需求:
方案1:使用Material UI 内置的component属性(最推荐)
MUI的TableRow组件支持自定义渲染的根元素,直接把它指定为react-router-dom的Link即可,完全符合结构规范:
import { Link } from 'react-router-dom'; import { TableRow, TableCell } from '@mui/material'; <TableRow key={index} component={Link} // 核心配置:TableRow根元素渲染为Link to={`/edit/${apiData.id}/${apiData.name}/${apiData.email}`} style={{ textDecoration: 'none', color: 'inherit' }} // 清除Link默认的下划线和文字颜色 > <TableCell align="left" style={{ paddingLeft: 40 }}> {apiData.name} </TableCell> <TableCell align="left">{apiData.email}</TableCell> <TableCell align="left">{apiData.status}</TableCell> <TableCell align="left">{roles}</TableCell> <TableCell align="right" style={{ paddingRight: 40 }}> <RoleButton onClick={(e) => { e.stopPropagation(); // 阻止点击事件冒泡到TableRow,避免触发跳转 handleRoleChange(); }} > {roles === "Admin" ? "Set as User" : "Set as Admin"} </RoleButton> </TableCell> </TableRow>
这个方案的优点是原生保留Link的所有特性(比如右键打开新标签页、Ctrl+点击新标签打开等浏览器默认链接行为),不需要额外写逻辑。
方案2:使用useNavigate钩子实现点击跳转
如果你不想用Link作为行根元素,可以用编程式导航的方式实现:
import { useNavigate } from 'react-router-dom'; import { TableRow, TableCell } from '@mui/material'; // 组件内先初始化navigate const navigate = useNavigate(); <TableRow key={index} onClick={() => navigate(`/edit/${apiData.id}/${apiData.name}/${apiData.email}`)} style={{ cursor: 'pointer' }} // 显示可点击的鼠标样式 > <TableCell align="left" style={{ paddingLeft: 40 }}> {apiData.name} </TableCell> <TableCell align="left">{apiData.email}</TableCell> <TableCell align="left">{apiData.status}</TableCell> <TableCell align="left">{roles}</TableCell> <TableCell align="right" style={{ paddingRight: 40 }}> <RoleButton onClick={(e) => { e.stopPropagation(); handleRoleChange(); }} > {roles === "Admin" ? "Set as User" : "Set as Admin"} </RoleButton> </TableCell> </TableRow>
这个方案的优点是结构完全和原生表格一致,缺点是默认不支持链接的右键菜单等原生行为,如果需要可以额外加配置实现。
内容的提问来源于stack exchange,提问作者ahmedskulj10
相关产品推荐
相关产品推荐

