使用react-resizable,可封装了一个ResizeableTable公共组件
(可适用于展示列动态变化和可拖拽调节表格,例如下图形式的表格)
1.安装依赖
yarn add react-resizable
2.封装公共组件ResizeableTable组件(ResizeableTable.js)
import * as React from 'react';
import { Table } from 'antd';
import { Resizable } from 'react-resizable';
import Emitter from '../utils/Emitter';
import './resizeable-table.less';
class ResizeableTitle extends React.Component {
render() {
const { onResize, width, resizable, onClick, ...restProps } = this.props;
if (!width || resizable) {
return <th {...restProps} />;
}
return (
<Resizable
width={width}
height={0}
handle={<span className="react-resizable-handle" onClick={(e) => { e.stopPropagation(); }} />}
onResize={onResize}
onResizeStart={() => { this.resizing = true; }}
onResizeStop={() => { setTimeout(() => { this.resizing = false; }); }}
draggableOpts={{ enableUserSelectHack: false }} >
<th
{...restProps}
onClick={(...args) => { if (!this.resizing && onClick) { onClick(...args); } }}
style={{
...restProps?.style,
width: `${width}px`,
}}
/>
</Resizable>
);
}
}
class ResizeableTable extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
columns: props.columns
};
}
components = {
header: {
cell: ResizeableTitle, // 动态拖拽设置列宽
}
};
componentDidMount() {
// 监听columnsChanged事件
Emitter.addListener('columnsChanged', (columns) => { this.setState({ columns: columns }); });
const handlers = document.querySelectorAll(
'.react-resizable .react-resizable-handle'
);
handlers.forEach((handler) => handler.addEventListener('click', () => { return false; }));
}
componentWillUnmount() {
Emitter.removeListener('columnsChanged', (columns) => { this.setState({ columns: columns }); });
}
render() {
const columns = this.state.columns.map((col, index) => ({
...col,
onHeaderCell: (column) => ({
width: column.width,
onResize: this.handleResize(index)
})
}));
const components = {
...this.props.components,
...this.components
};
return <Table {...this.props} columns={columns} components={components} />;
}
// 拖拽后更新表格宽度
handleResize = (index) => (e, { size }) => {
e.stopImmediatePropagation();
this.setState(({ columns }) => {
const nextColumns = [...columns];
nextColumns[index] = {
...nextColumns[index],
width: size.width
};
return { columns: nextColumns };
});
};
}
export default ResizeableTable;
3.使用封装公共组件
引入ResizeableTable.js
import ResizeableTable from '../../../../components/ResizeableTable';
添加监听事件
Emitter.emit('columnsChanged', columns); // 可拖拽宽度表格 需要配合此事件更新内部表格
使用ResizeableTable组件
<ResizeableTable size="small" columns={columns} dataSource={data} pagination={false} scroll={{ y: (clientHeight - 235) }} onChange={this.onTableChange} /></div>