近来一直在用React
+Ant Design
进行开发,然后用了一段时间发现其中的Table
组件却不支持拖动列调整列宽的功能。对于习惯了Vue
+ElementUI
的我,多多少少有点不方便。对于ElementUI
的Table
组件,将border
属性设置成true
之后便可拖动列宽。
方案
在网上一番查找之后,看到其中一种方案是借助于React-Resizable
实现拖动列宽效果。关于React-Resizable
的详细用法,可以查看官方Github主页https://github.com/react-grid-layout/react-resizable 。
简单的说,就是借助Antd
的Table
组件的components
参数,覆盖Table
组件header
的
cell
的渲染方式,在cell
里嵌套一层React-Resizable
库的Resizable
组件,通过Resizable
组件的onResize
事件参数,进而调整Table
列组件的宽度,达到调整列宽的目的。
其中Table
组件的components
参数具体属性如下:
export interface TableComponents<RecordType> {
table?: CustomizeComponent;
header?: {
wrapper?: CustomizeComponent;
row?: CustomizeComponent;
cell?: CustomizeComponent;
};
body?:
| CustomizeScrollBody<RecordType>
| {
wrapper?: CustomizeComponent;
row?: CustomizeComponent;
cell?: CustomizeComponent;
};
}
代码实现
import {
Table } from "antd";
import React from "react";
import {
Resizable } from "react-resizable";
import "../node_modules/react-resizable/css/styles.css"; // 引入react-resizable样式,否则无法显示Resize样式
const dataSource = [
{
key: "1",
name: "张三",
age: 32,
address: "西湖区湖底公园1号"
},
{
key: "2",
name: "李四",
age: 42,
address: "西湖区湖底公园1号"
}
];
const columns = [
{
title: "姓名",
dataIndex: "name",
key: "name",
width: 110
},
{
title: "年龄",
dataIndex: "age",
key: "age",
width: 90
},
{
title: "住址",
dataIndex: "address",
key: "address",
width: 220
},
{
}
];
// 重写Table组件header单元格渲染方式
const ResizableTitle = (props) => {
const {
onResize, width, ...restProps } = props;
if (width === undefined) {
return <th {
...restProps}></th>;
}
return (
// 外包一层Resizable组件
// 其中onResize属性调用col.onResize方法
<Resizable width={
width} height={
0} onResize={
onResize}>
<th {
...restProps}></th>
</Resizable>
);
};
export default class MyTable extends React.Component {
constructor(props) {
super(props);
this.state = {
dataSource,
columns: columns.map((col) => {
// 注意:给每一列的onHeaderCell属性增加onResize方法,用于传递onResize事件
col.onHeaderCell = () => ({
width: col.width,
onResize: this.handleResize(col)
});
return col;
})
};
}
// Table 组件 components
components = {
header: {
cell: ResizableTitle
}
};
// 动态修改col.width属性
handleResize = (column) => (e, {
size }) => {
this.setState(({
columns }) => {
columns.forEach((item) => {
if (item === column) {
item.width = size.width;
}
});
return {
columns };
});
};
render() {
return (
<div>
<Table
bordered
dataSource={
this.state.dataSource}
columns={
this.state.columns}
components={
this.components}
/>
</div>
);
}
}
源码codesandbox地址请查看:https://codesandbox.io/s/antd-table-column-resize-width-jlpdtz?file=/src/MyTable.js
最终效果
拓展阅读:
https://blog.csdn.net/m0_58016522/article/details/123470541
参考链接:
https://blog.csdn.net/ysunshine512/article/details/88948545