react+antd实现Table拖拽调整列宽

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{} 包裹一下试下。

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 38
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 38
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值