惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
人人都是产品经理
人人都是产品经理
IT之家
IT之家
T
The Blog of Author Tim Ferriss
V
V2EX
博客园 - 聂微东
The Cloudflare Blog
Blog — PlanetScale
Blog — PlanetScale
A
About on SuperTechFans
U
Unit 42
Vercel News
Vercel News
L
LangChain Blog
博客园 - 司徒正美
H
Help Net Security
Recent Announcements
Recent Announcements
Recorded Future
Recorded Future
V
Visual Studio Blog
Jina AI
Jina AI
Microsoft Azure Blog
Microsoft Azure Blog
GbyAI
GbyAI
Y
Y Combinator Blog
C
Check Point Blog
博客园 - 三生石上(FineUI控件)
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
J
Java Code Geeks
The Register - Security
The Register - Security
The GitHub Blog
The GitHub Blog
B
Blog RSS Feed
F
Fortinet All Blogs
B
Blog
G
Google Developers Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
云风的 BLOG
云风的 BLOG
爱范儿
爱范儿
MongoDB | Blog
MongoDB | Blog
F
Full Disclosure
有赞技术团队
有赞技术团队
罗磊的独立博客
博客园_首页
MyScale Blog
MyScale Blog
aimingoo的专栏
aimingoo的专栏
Google DeepMind News
Google DeepMind News
M
MIT News - Artificial intelligence
N
Netflix TechBlog - Medium
Engineering at Meta
Engineering at Meta
量子位
I
InfoQ
小众软件
小众软件
P
Proofpoint News Feed

博客园_首页

Plist 二进制格式 Milvus 和 PGVector,哪个更好? OpenClaw 已过时?在 VS Code 中运行 Hermes Agent! 第30篇文章:一个大三计科生的自白 Manim如何在数学公式中完美显示中文? Docker 部署 RocketMQ 5 并发编程核心概念辨析 C#事务处理最佳实践:别再让“主表存了、明细丢了”的破事发生 CLI 是什么?为什么大厂突然集体卷命令行? 【从0到1构建一个ClaudeAgent】协作-自主Agent UIImageView 设置图片不生效的原因排查 最小二乘问题详解20:无先验约束下的增量式SFM自由网平差 痞子衡嵌入式:大话双核i.MXRT1180之XIP应用里借助MU实现可靠Flash IAP的方法 AI Chat 封装, SemanticKerne.AiProvider.Unified 已发布 Windows下右键编辑js文件无法打开记事本——在注册表中使用环境变量 在后台服务中使用 Scoped 服务,为什么总是报错? H200 安装驱动并使用sglang启动模型 wireshark 抓包Trap上报告警内容 我用 AI 辅助开发了一系列小工具(2):图片压缩工具 [A Primer On MC and CC] 2.1 Memory Consistency 1 - 指令重排序和 SC 模型 Oracle数据库SCN推进技术详解与实践指南 玩转控件:封装个带图片的Label控件 Claude Code 4.7 真正该升级的不是模型,而是你的工作流 前端小白一句话,AI 帮我做了个颜值拉满的桌面媒体播放器。当代码不再是门槛,一句话编程就是现实。 5. WorkBuddy: 小龙虾的灵魂三件套,让你的小龙虾不只是工具 SQLite 分片方案实战:三种分片策略的深度对比 告别简陋 UI!一款基于 Fluent Design 和基于 WinUI 的开源免费、现代化的 Avalonia UI 控件库 关于二进制排列组合枚举的总结 AI开发-python-LangGraph框架(3-27-LangGraph从零实现大模型智能决策工作流) ElasticSearch主分片和副本分片概念详解 【002】HTTPS 粗解:证书、TLS 握手与对后端配置的影响 Hermes Agent 一周暴涨五万 Star,但我劝你别急着追 明明连接的是Redis的DB0,为什么能查到DB3的数据? 【从0到1构建一个ClaudeAgent】协作-Agent团队 熟悉电子元器件之后,电子小白下一步该怎么走? MAF快速入门(23)通过C#类定义Skills .NET 高级开发 | 手写一个对象映射框架 FastAPI数据库ORM怎么选?我肝了三个Demo后,终于不再纠结了 mysqldump 参数拾遗:在遗忘与铭记之间 C# .NET 周刊|2026年3月5期 Claude code入门 - 陈彦斌 一文学习入门 ThingsBoard 开源物联网平台 GitHub 热门项目 | 2026年04月16日 如何为GIT设置全局勾子,为每次提交追加信息 Number.isFinite和isFinite与isNaN()和Number.isNaN的区别 PortSwigger SQL注入LAB2 推荐一个测试人必备的Skills,从功能到性能全搞定(附详细实操和安装下载方式) 筑基期:掌握Odoo基础核心知识点02(Odoo XML 开发方式详解) GLM模型这么火,咱们用vllm也咧一个呗! 深入理解 AbortController:从底层原理到跨语言设计哲学 字符串学习笔记 多租户系统框架的基础模块设计和分析设计 Apache SeaTunnel Zeta 为什么能做到“又快又稳”? AI开发-python-LangGraph框架(3-26-LangGraph基本概念及第一个简单样例) Vue 3 组件通信,别只会用 Props 和 Emits 了,这几个狠活儿你得看看 ElasticSearch7.X版本配置密码 用Manim实现动态交点计算--从一个动点问题说起 团结引擎+Addressable+Instant Game打包抖音小游戏 function call 实战:让 LLM 自动判断 pod 异常、调用日志工具并完成故障分析 bubseek —— 让 Agent 的足迹,变成团队的洞察 通过 C# 读取并导出 PDF 书签 如何用 GitHub Actions 实现 Steam 自动化发布 【从0到1构建一个ClaudeAgent】并发-后台任务 .NET 高级开发 | 定制 ASP.NET Core 框架 电子小白:什么是运算放大器(运放) zero2Agent:面向大厂面试的 Agent 工程教程,从概念到生产的完整学习路线 堆上的ORW HC32F460 USB CDC通信异常:非对齐访问异常排查 20260413-Hyperbridge 攻击事件:发生在默克尔山上的验证绕过 那些喊着AI 要淘汰你的人,正在靠你的焦虑赚大钱! 深度学习进阶(八)Swin Transformer 最小二乘问题详解19:带先验约束的增量式SFM优化与实现 SnapTranslate 3.0 正式发布:全局划词翻译 + 完整英语学习闭环,一站式搞定查词、记词、复习 工作的意义、工作的困难认知再思考 .NET + AI 进阶实战:基于类的技能开发 - 打造可治理的 Agent 能力模块 【从0到1构建一个ClaudeAgent】规划与协调-技能 上周热点回顾(4.6-4.12) 电子小白的工具三件套:面包板、杜邦线、万能板 单表五亿数据的查询优化 | Mysql、StarRocks 2. WorkBuddy:从“我是谁”到“帮我干活” C# 如何减少代码运行时间:7 个实战技巧 基于HelixToolkit.SharpDX 渲染3D模型 - 笺上知微 从零开始的双臂具身VLA起源及现阶段发展综述 - SkyXZ 记对 xonsh shell 的使用, 脚本编写, 迁移及调优 - pluvium27 受够了Vibe Coding的失控?换个起点,让AI事半功倍 从开始配置漏洞环境到漏洞复现流程 - 難しい 关于10年工作经验的程序员对OpenClaw的实战经验分享以及看法 - 虚无境 Any metadata 的内存布局 C# .NET 周刊|2026年3月2期 - InCerry 我帮你测过了,测试圈排名第二的 Skill 依然很牛逼 Skill Discovery | 无监督技能发现的经典工作总结 - MoonOut 上下文工程是什么?过时了么?一文讲明白! - 一枫说码 开了 TUN 模式还是直连?90% 的人都踩过这个坑 AScript扩展多种脚本语言 - rockey627 AI 学习笔记:Agent 的记忆机制 你能被装进一个文件里吗?——7 万人把同事"蒸馏"成了 AI - 我没有三颗心脏 Claude Code 通关手册(七):给 AI 装上技能包——Skills 完全指南 - 暮色之狐 在浏览器中快速编辑代码:VSCode Web 集成实践 - Newbe36524 蒸馏自己 skill?基于 Deepseek 的蒸馏器,丐版蒸馏方式,简单便捷 - To_Carpe_Diem Spring AI Aliababa和AgentScope,哪个更好? - 苏三说技术
React 可拖拽列宽 + 点击行选中 ProTable 封装笔记
土豆儿哥 · 2026-05-22 · via 博客园_首页

平时做后台管理系统,Ant Design Pro 的 ProTable 用得特别多,但原生组件缺少列宽拖拽调整点击行选中这两个高频功能,每次都要重复写逻辑。

所以我把这两个功能封装成了通用组件,后续项目直接复用,这里整理成笔记方便自己查阅。

一、整体思路

把功能拆成两部分解耦:

  1. 列宽拖拽核心逻辑:独立封装可调整表头组件,无业务侵入
  2. ProTable 业务封装:集成列宽拖拽 + 点击行选中 + 选中状态受控/非受控 + 暴露清空选中方法

两个文件配合使用,开箱即用,支持 TypeScript,兼容 ProTable 所有原生属性。


二、列宽拖拽表头封装(ResizableTitle.tsx)

这是列宽拖拽的核心,基于原生 th 实现鼠标按下、移动、抬起的完整拖拽逻辑,最小宽度限制 80px,右侧有拖拽触发区,体验接近 Excel。

import React, { useState, useCallback } from 'react';

// 表格列配置类型
export interface TableColumnType {
  width?: number;
  title?: React.ReactNode;
  dataIndex?: string;
  key?: string;
  [key: string]: any;
}

// 表头组件
interface ResizableTitleProps {
  width?: number;
  onResize?: (width: number) => void;
  [key: string]: any;
}

const ResizableTitle: React.FC<ResizableTitleProps> = (props) => {
  const { width, onResize, ...restProps } = props;
  const [isResizing, setIsResizing] = useState(false);

  // 鼠标按下开始拖拽
  const handleMouseDown = useCallback((e: React.MouseEvent) => {
    const thRect = e.currentTarget.getBoundingClientRect();
    // 只在右侧 10px 区域触发拖拽
    const isOnEdge = e.clientX > thRect.right - 10;
    if (!isOnEdge) return;

    e.preventDefault();
    setIsResizing(true);

    const startX = e.clientX;
    const startWidth = thRect.width;

    // 拖拽中实时更新宽度
    const handleMouseMove = (moveEvent: MouseEvent) => {
      const diff = moveEvent.clientX - startX;
      const newWidth = Math.max(80, startWidth + diff);
      onResize?.(newWidth);
    };

    // 松开鼠标结束拖拽
    const handleMouseUp = () => {
      setIsResizing(false);
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    };

    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);
  }, [onResize]);

  return (
    <th
      {...restProps}
      onMouseDown={handleMouseDown}
      style={{
        width,
        position: 'relative',
        paddingRight: '10px',
        cursor: isResizing ? 'col-resize' : undefined,
        userSelect: 'none',
      }}
    >
      {/* 拖拽触发区域 */}
      <span
        style={{
          position: 'absolute',
          right: 0,
          top: 0,
          bottom: 0,
          width: '10px',
          cursor: 'col-resize',
          backgroundColor: 'transparent',
        }}
        onMouseEnter={(e) => {
          e.currentTarget.style.backgroundColor = 'rgba(22, 119, 255, 0.1)';
        }}
        onMouseLeave={(e) => {
          if (!isResizing) {
            e.currentTarget.style.backgroundColor = 'transparent';
          }
        }}
      />
      {props.children}
    </th>
  );
};

// 注入到 ProTable 表头
export const components = {
  header: {
    cell: ResizableTitle,
  },
};

// 处理列配置,绑定拖拽回调
export const getMergeColumns = (
  columns: TableColumnType[],
  setColumns: React.Dispatch<React.SetStateAction<TableColumnType[]>>
) => {
  return columns.map((col, index) => ({
    ...col,
    onHeaderCell: (column: TableColumnType) => ({
      width: column.width,
      onResize: (newWidth: number) => {
        setColumns((prev: TableColumnType[]) => {
          const next = [...prev];
          next[index] = {
            ...next[index],
            width: newWidth,
          };
          return next;
        });
      },
    }),
  }));
};

export default ResizableTitle;

核心要点

  • 拖拽只触发在表头右侧 10px 区域,不影响正常点击
  • 最小宽度 80px,防止列被缩没
  • 鼠标悬浮拖拽区有淡蓝色提示,体验更好
  • 对外暴露 componentsgetMergeColumns 供 ProTable 集成

三、ProTable 业务封装(MyProTable.tsx)

在 ProTable 基础上集成:

  • 列宽拖拽
  • 点击行选中(支持单选/多选)
  • 选中状态支持外部受控 / 内部非受控
  • 暴露 clearSelected 方法清空选中
  • 搜索栏按钮顺序调整(查询在前,重置在后)
  • 完全兼容 ProTable 原有属性
import { ProTable, type ProTableProps } from '@ant-design/pro-components';
import React, { forwardRef, useImperativeHandle, useState } from 'react';
import { components, getMergeColumns } from '../ResizableTitle';

// 暴露给父组件的方法
export interface MyProTableRef {
  clearSelected: () => void;
}

// 扩展 ProTable 属性
export type MyProTableProps<
  T extends Record<string, any>,
  U extends Record<string, any> = Record<string, any>,
  ValueType = 'text'
> = ProTableProps<T, U, ValueType> & {
  enableRowSelect?: boolean; // 是否开启点击选中
  selectedRowKeys?: React.Key[]; // 外部受控选中key
  onSelectedChange?: (keys: React.Key[], rows: T[]) => void; // 选中变化回调
  multiple?: boolean; // 是否多选
};

const MyProTableInner = <
  T extends Record<string, any>,
  U extends Record<string, any> = Record<string, any>,
  ValueType = 'text'
>(
  props: MyProTableProps<T, U, ValueType>,
  ref: React.ForwardedRef<MyProTableRef>
) => {
  const {
    enableRowSelect = true,
    selectedRowKeys,
    onSelectedChange,
    multiple = false,
    rowKey = 'id' as keyof T,
    columns = [],
    ...restProps
  } = props;

  // 内部选中状态(非受控模式)
  const [innerKeys, setInnerKeys] = useState<React.Key[]>([]);
  const finalKeys = selectedRowKeys ?? innerKeys;

  // 列宽拖拽状态
  const [renderColumns, setRenderColumns] = useState<any[]>(columns);
  const resizeColumns = getMergeColumns(renderColumns, setRenderColumns as any);

  // 选中变化统一处理
  const handleChange = (keys: React.Key[], rows: T[]) => {
    if (selectedRowKeys === undefined) setInnerKeys(keys);
    onSelectedChange?.(keys, rows);
  };

  // 获取行唯一 key
  const getRowKey = (record: T): React.Key => {
    if (typeof rowKey === 'function') return rowKey(record);
    return record[rowKey] as React.Key;
  };

  // 点击行触发选中
  const handleClick = (record: T) => {
    if (!enableRowSelect) return;
    const key = getRowKey(record);

    let newKeys: React.Key[];
    if (multiple) {
      // 多选:切换当前行选中状态
      newKeys = finalKeys.includes(key)
        ? finalKeys.filter((k) => k !== key)
        : [...finalKeys, key];
    } else {
      // 单选:只保留当前行或清空
      newKeys = finalKeys.includes(key) ? [] : [key];
    }

    // 匹配选中行数据
    const selectedRows = newKeys
      .map((k) => restProps.dataSource?.find((item) => getRowKey(item) === k))
      .filter((item): item is T => !!item);

    handleChange(newKeys, selectedRows);
  };

  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    clearSelected: () => handleChange([], []),
  }));

  return (
    <ProTable<T, U, ValueType>
      {...restProps}
      rowKey={rowKey}
      columns={resizeColumns as any}
      components={components} // 注入可拖拽表头
      onRow={(record) => ({
        ...restProps.onRow?.(record),
        onClick: () => handleClick(record), // 绑定点击行事件
      })}
      rowClassName={(record, index, indent) => {
        const key = getRowKey(record);
        const isSelected = finalKeys.includes(key);
        let customClass = '';

        // 兼容外部传入的 className
        if (typeof restProps.rowClassName === 'function') {
          customClass = restProps.rowClassName(record, index, indent);
        } else if (typeof restProps.rowClassName === 'string') {
          customClass = restProps.rowClassName;
        }

        return isSelected ? `table-row-selected ${customClass}` : customClass;
      }}
      // 搜索栏:查询按钮在前,重置按钮在后
      search={{
        ...restProps.search,
        optionRender: (_searchConfig, _formProps, dom) => {
          if (!dom || dom.length < 2) return dom;
          const [resetBtn, submitBtn] = dom;
          return [submitBtn, resetBtn];
        },
      }}
    />
  );
};

// 转发 ref,支持泛型
const MyProTable = forwardRef(MyProTableInner) as <
  T extends Record<string, any>,
  U extends Record<string, any> = Record<string, any>,
  ValueType = 'text'
>(
  props: MyProTableProps<T, U, ValueType> & { ref?: React.ForwardedRef<MyProTableRef> }
) => React.ReactElement;

export default MyProTable;

样式补充(全局加一行即可)

选中行高亮样式,在全局 global.less 中添加:

.table-row-selected {
  background-color: rgba(22, 119, 255, 0.1) !important;
}

四、使用示例

封装完后使用非常简单,和普通 ProTable 用法几乎一致:

import React, { useRef } from 'react';
import MyProTable, { MyProTableRef } from './MyProTable';

const DemoPage = () => {
  const tableRef = useRef<MyProTableRef>(null);

  const columns = [
    { title: 'ID', dataIndex: 'id', width: 100 },
    { title: '姓名', dataIndex: 'name', width: 150 },
    { title: '年龄', dataIndex: 'age', width: 120 },
    { title: '地址', dataIndex: 'address' },
  ];

  // 选中回调
  const handleSelect = (keys, rows) => {
    console.log('选中keys:', keys);
    console.log('选中数据:', rows);
  };

  return (
    <div>
      <button onClick={() => tableRef.current?.clearSelected()}>
        清空选中
      </button>

      <MyProTable
        ref={tableRef}
        columns={columns}
        rowKey="id"
        multiple={true} // 开启多选
        onSelectedChange={handleSelect}
        request={async () => {
          // 模拟接口
          return {
            data: [
              { id: 1, name: '张三', age: 20, address: '北京' },
              { id: 2, name: '李四', age: 25, address: '上海' },
            ],
            total: 2,
          };
        }}
      />
    </div>
  );
};

export default DemoPage;

五、使用心得

  1. 列宽拖拽和业务完全解耦,后续想用到普通 Table 也能快速抽离
  2. 点击行选中支持单选/多选,满足大部分列表场景
  3. 选中状态支持受控/非受控,适配表单联动或独立使用
  4. 完全兼容 ProTable 原生属性,老项目改造成本极低
  5. 封装后项目里只需要引入 MyProTable,不用再写重复逻辑

这个封装基本覆盖了后台系统表格 90% 的常用场景,后续直接复制这两个文件就能用。