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

Material UI中Tooltip包裹TableRow导致布局错乱的解决方法

问题原因

Material UI的Tooltip默认会渲染一个<div>元素,而HTML表格的<tbody>只允许<tr>作为直接子元素。把<div>插在<tbody>和<tr>之间会完全破坏表格的布局规则,导致所有列被压缩到第一列。

解决方案

方案一:让Tooltip直接渲染为TableRow(推荐)

修改overrideTr的逻辑,将Tooltip的component属性指定为TableRow,这样Tooltip会直接以TableRow的身份渲染,不会插入额外的div破坏布局:

overrideTr={({ defaultRender }) => {
  const batch = defaultRender?.[0]?.props?.row;
  return (
    <Tooltip 
      title={batch.batchId}
      component={TableRow} // 关键配置:让Tooltip渲染为TableRow组件
      onClick={() => {
        setCurrentBatch({ ...batch });
        history.push(`/connect/summary/messages`);
      }}
      selected={isCurrentBatch(batch?.batchId)}
      sx={{ cursor: "pointer" }}
      hover
    >
      {defaultRender}
    </Tooltip>
  );
}}

方案二:手动控制Tooltip显示状态(灵活自定义)

如果需要保留独立的TableRow组件,可以通过ref绑定行元素,手动监听鼠标事件控制Tooltip的开关,避免插入非法结构:

import { useState, useRef } from 'react';

// ...

overrideTr={({ defaultRender }) => {
  const batch = defaultRender?.[0]?.props?.row;
  const [tooltipOpen, setTooltipOpen] = useState(false);
  const rowRef = useRef(null);

  return (
    <>
      <TableRow
        ref={rowRef}
        onClick={() => {
          setCurrentBatch({ ...batch });
          history.push(`/connect/summary/messages`);
        }}
        selected={isCurrentBatch(batch?.batchId)}
        sx={{ cursor: "pointer" }}
        hover
        onMouseEnter={() => setTooltipOpen(true)}
        onMouseLeave={() => setTooltipOpen(false)}
      >
        {defaultRender}
      </TableRow>
      <Tooltip
        open={tooltipOpen}
        title={batch.batchId}
        anchorEl={rowRef.current}
        disableInteractive
      />
    </>
  );
}}

内容的提问来源于stack exchange,提问作者HubertBlu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 09:40:32