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

React-Table v6双表格联动:行高亮与同步垂直滚动实现方案

React-Table v6 双表格同步交互实现方案(无原生事件监听)

一、行悬停同步高亮实现

通过React状态共享当前悬停的行标识,结合React-Table的行属性配置实现同步高亮:

  • 用useState维护当前悬停的行ID(或数据唯一标识)
  • 两个表格的getTrProps方法根据状态判断是否添加高亮类
  • 第一个表格的行监听React合成事件onMouseEnter和onMouseLeave,更新共享状态

示例代码片段:

const [hoverRowId, setHoverRowId] = useState(null);

// 左侧表格行属性配置
const getLeftTableTrProps = (state, rowInfo) => {
  if (!rowInfo) return {};
  return {
    onMouseEnter: () => setHoverRowId(rowInfo.row.id),
    onMouseLeave: () => setHoverRowId(null),
    className: rowInfo.row.id === hoverRowId ? 'highlight-row' : ''
  };
};

// 右侧表格行属性配置
const getRightTableTrProps = (state, rowInfo) => {
  if (!rowInfo) return {};
  return {
    className: rowInfo.row.id === hoverRowId ? 'highlight-row' : ''
  };
};

高亮样式:

.highlight-row {
  background-color: #f5f7fa;
}

二、垂直滚动同步实现

通过受控状态管理滚动位置,让两个表格的滚动容器共享同一scrollTop值:

  • 用useState维护当前滚动位置scrollTop
  • 为两个表格的外层滚动容器设置scrollTop={scrollTop}受控属性
  • 监听容器的React合成事件onScroll,更新scrollTop状态

示例代码片段:

const [scrollTop, setScrollTop] = useState(0);

const handleScroll = (e) => {
  // 避免循环更新,仅当滚动位置不一致时更新状态
  if (e.target.scrollTop !== scrollTop) {
    setScrollTop(e.target.scrollTop);
  }
};

// 表格容器样式:实现并排+独立滚动
const tableContainerStyle = {
  width: '50%',
  overflowY: 'auto',
  height: '400px'
};

// 视觉统一样式:去除中间边框,模拟单表格效果
const leftTableStyle = {
  borderRight: 'none'
};
const rightTableStyle = {
  borderLeft: 'none'
};

// 渲染双表格
return (
  <div style={{ display: 'flex' }}>
    <div style={tableContainerStyle} onScroll={handleScroll} scrollTop={scrollTop}>
      <ReactTable
        data={leftTableData}
        columns={leftColumns}
        getTrProps={getLeftTableTrProps}
        style={leftTableStyle}
      />
    </div>
    <div style={tableContainerStyle} onScroll={handleScroll} scrollTop={scrollTop}>
      <ReactTable
        data={rightTableData}
        columns={rightColumns}
        getTrProps={getRightTableTrProps}
        style={rightTableStyle}
      />
    </div>
  </div>
);

关键说明

  • 所有交互逻辑基于React状态和合成事件实现,完全遵循声明式开发风格,无需直接操作DOM或添加原生事件监听
  • 行标识优先使用数据唯一ID而非索引,避免数据排序后高亮错位
  • 滚动同步时通过判断滚动位置是否相等,避免不必要的状态更新,提升性能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:35:24