黑白梦

使用 pro-components 的 DragSortTable 拖动排序表格

博客管理端一直使用了 @ant-design/pro-components 库,减少了很多样板代码,列表、表单代码都比较简洁。

但有个问题,拖拽表格需要引入 react-sortable-hoc 并使用大量的示例代码,才能实现拖拽,可维护性不太好。而且项目升级 react 18 依赖后,因 react-sortable-hoc 内部的 peerDependencies 无该版本,导致无法直接使用 npm i 安装依赖,需要带上 --legacy-peer-deps

最近又把 @ant-design/pro-components 升级了,再去文档查看,发现已经有可拖拽表格组件 DragSortTable 了。使用非常简单:

<DragSortTable
  headerTitle="拖拽排序"
  columns={[
    {
      title: '排序',
      dataIndex: 'sort',
      width: 60,
      className: 'drag-visible',
      hideInTable: disabled,
    },
    // 其他字段
  ]}
  rowKey="id"
  dataSource={dataSource}
  pagination={false}
  toolBarRender={false}
  search={false}
  dragSortKey="sort"
  onDragSortEnd={handleDragSortEnd}
/>

回调函数直接返回排序完成后的数组,设置即可:

const handleDragSortEnd = (beforeIndex: number, afterIndex: number, newDataSource: any) => {
  handleChange(newDataSource);
};
本文收录于专栏
收集一些好用的前端开源库,主要是 npm 包