use-antd-resizable-header
antd 表格头拖拽 Hook,兼容 Table ProTable
预览
安装
yarn add use-antd-resizable-header
注意事项
- columns 为常量时,提到组件外,或使用
React.useMemo
,React.Ref
包裹常量 - 默认拖动颜色为
#000
,可通过global
或设置css变量--atrh-color
设置颜色 - 最后一列不能拖动,请保持最后一列的自适应,若最后一列传入宽度,会把传入的宽度作为最小宽度(默认 120)
Example
import useATRH from 'use-antd-resizable-header';
import 'use-antd-resizable-header/dist/style.css';
const columns = [];
function App() {
const { components, resizableColumns, tableWidth } = useATRH(columns);
return (
<>
<Table
columns={resizableColumns}
components={components}
dataSource={data}
scroll={{ x: tableWidth }}
></Table>
<ProTable
columns={resizableColumns}
components={components}
dataSource={data}
scroll={{ x: tableWidth }}
></ProTable>;
</>
);
}
基本用例
/* index.css */
--atrh-color: red;
import ProTable from '@ant-design/pro-table'; // or import { Table } from 'antd'
import useATRH from 'use-antd-resizable-header';
import 'use-antd-resizable-header/dist/style.css';
import './index.css';
const columns: ProColumns[] = [
{
title: 'id',
dataIndex: 'id',
width: 300,
},
{
title: 'name',
dataIndex: 'name',
},
];
const dataSource = [
{
id: 1,
name: 'zhangsan',
},
{
id: 2,
name: 'lisi',
},
];
function App() {
const { resizableColumns, components, tableWidth } = useATRH(columns);
return (
<ProTable
columns={resizableColumns}
components={components}
scroll={{ x: tableWidth }}
dataSource={dataSource}
></ProTable>
);
}
export default App;
基本用例 - 搭配 Typography 实现 title 溢出时 tooltip
/* index.css */
--atrh-color: red;
// utils.tsx
export const genEllipsis = (text: string, copyable?: boolean, stopPropagation?: boolean) => {
let _text = isNil(text) ? '' : String(text);
if ([null, undefined, ''].includes(text)) _text = '-';
return (
<Typography.Text
style={{
width: '100%',
margin: 0,
padding: 0,
color: 'inherit',
}}
onClick={(e) => (stopPropagation ? e?.stopPropagation() : null)}
title=" "
copyable={
copyable && text
? {
text,
tooltips: ['', ''],
}
: undefined
}
ellipsis={text ? { tooltip: text } : false}
>
{_text}
</Typography.Text>
);
};
// index.tsx
import ProTable from '@ant-design/pro-table'; // or import { Table } from 'antd'
import useATRH from 'use-antd-resizable-header';
import { genEllipsis } from './utils.tsx';
import 'use-antd-resizable-header/dist/style.css';
import './index.css';
const columns: ProColumns[] = [
{
title: 'id',
dataIndex: 'id',
width: 300,
},
{
title: 'name',
dataIndex: 'name',
},
];
const dataSource = [
{
id: 1,
name: 'zhangsan',
},
{
id: 2,
name: 'lisi',
},
];
function App() {
const { resizableColumns, components, tableWidth } = useATRH(columns);
let cols = [...resizableColumns];
cols = columns.map((item) => ({
...item,
title: genEllipsis(item.title as string, false, true),
}));
return (
<ProTable
columns={cols}
components={components}
scroll={{ x: tableWidth }}
dataSource={dataSource}
></ProTable>
);
}
export default App;