利用react-resizable实现antd表格头宽度可以拖拽调节

1.创建ResizeAbleTable文件夹

1.1 index.js

import { Table } from "antd4";
import React, { useEffect, useState } from "react";
import { Resizable } from "react-resizable";
import { Tooltip } from 'antd';
import styles from './index.less';

const textEllipsis = {
	whiteSpace: 'nowrap',
	textOverflow: 'ellipsis',
	overflow: 'hidden',
};

/**
 * 可伸缩列
 * @param props
 * @returns
 */
const ResizableTable = (props) => {

	const [columns, setColumns] = useState([]);

	useEffect(() => {
		if (props.columns) {
			setColumns(props.columns)
		}
	}, [props.columns]);

	const handleResize = (index) => (_, { size }) => {
		const newColumns = [...columns];
		newColumns[index] = {
			...newColumns[index],
			width: size.width,
		};
		setColumns(newColumns);
	};

	const mergeColumns = columns.map((col, index) => ({
		...col,
		render: (text, record, index) => {
			if (col.needRender) { //自定义render
				return col.render(text, record, index);
			}
			return ( //统一render
				<Tooltip title={text} placement='topLeft'>
					<div style={{ width: col.width, ...textEllipsis }}>{text}</div>
				</Tooltip>
			)
		},
		onHeaderCell: (column) => ({
			width: column.width ?? 80,
			onResize: handleResize(index),
		}),
	}));


	return (
		<div className={styles.resizeTable}>
			<Table
				{...props}
				bordered
				components={{
					header: {
						cell: ResizableTitle
					}
				}}
				scroll={{ x: 900 }}
				columns={mergeColumns}
				dataSource={props.dataSource}
			/>
		</div>
	)
}

export default ResizableTable

const ResizableTitle = (props) => {
	const { onResize, width, ...restProps } = props

	if (!width) {
		return <th {...restProps} />
	}
	return (
		<Resizable
			width={width}
			height={0}
			handle={
				<span
					className="react-resizable-handle"
					onClick={(e) => {
						e.stopPropagation()
					}}
				/>
			}
			onResize={onResize}
			draggableOpts={{ enableUserSelectHack: false }}
		>
			<th {...restProps} />
		</Resizable>
	)
}

1.2 index.less

.resizeTable {
  :global {
    .react-resizable {
      position: relative;
      background-clip: padding-box;
    }
  
    .react-resizable-handle {
      position: absolute;
      width: 10px;
      height: 100%;
      bottom: 0;
      right: -5px;
      cursor: col-resize;
      background-image: none;
      z-index: 1;
    }
  
    .ant-table-filter-column,
    .ant-table-column-sorters {
      display: flex;
      /* co1umn 从上到下*/
      align-items: center;
      /* center代表水平方向 */
      justify-content: space-around;
      min-width: 70px;
    }
  
    .ant-table-thead>tr>th .ant-table-column-sorter {
      margin-top: -21px;
      display: table-cell;
      vertical-align: middle;
    }
  }
}

2.引入组件进行使用

<ResizableTable columns={ResettlementsColumn} dataSource={data} />

参考链接:

antd table 可伸缩列 react-resizable 多表头实现 - 简书 (jianshu.com)

posted @ 2023-06-16 18:04  天官赐福·  阅读(1703)  评论(0编辑  收藏  举报
返回顶端