react+antd用react-resizable实现Table拖拽调整列宽
npm下载依赖包
npm install react-resizable --save
如果上述报错缺依赖包react-draggable还需要引入react-draggable包,并重启项目
使用
import React, {PureComponent} from 'react';
import { Resizable } from 'react-resizable';
const ResizeableTitle = (props) => {
const { onResize, width, ...restProps } = props;
if ( !width ) {
return <th {...restProps} />
}
return (
<Resizable width={width} height={0} onResize={onResize}>
<th {...restProps} />
</ Resizable >
)
}
class Table extends PureComponent {
constructor(props) {
super(props);
}
this.state = {
columns: this.props.columns // 从父组件拿到表头 或者 直接将表头写到此处
}
components = {
header: {
cell: ResizeableTitle,
},
};
handleResize = index => (e, { size }) => {
this.setState(({ columns }) => {
const nextColumns = [...columns];
nextColumns[index] = {
...nextColumns[index],
width: size.width,
};
return { columns: nextColumns };
});
};
render() {
const columns = this.state.columns.map((col, index) => ({
...col,
onHeaderCell: column => ({
width: col.width // 100 没有设置宽度可以在此写死 例如100试下
onResize: this.handleResize(index),
}),
}));
return (
<Table
bordered
components={this.components}
columns={columns}
dataSource={this.props.data} // 从父组件取data数据或者直接在上面写data
/>
);
}
}
export default Table
注意
使用react-resizable 时必须引入其包中style.css文件,或者粘贴至自己的css中引用,否则不显示拖拽图标。
各位大佬是把react-resizable包里面有个 style.css引入自己的代码中,或者复制出来粘贴到自己的css中,我是粘贴到了自己的css里,就不复制出来了,下载的包里可以找到css代码。 css需要是全局的,如果不生效用:global{} 包裹一下试下。