三、效果
拆分组件
直接拿代码
components/ResizableTableModel/index.jsx
// components/ResizableTableModel/index.jsx // 可拖拽表格组件 import { useState } from 'react'; import { Table } from 'antd'; import { Resizable } from 'react-resizable'; import './index.css'; // 表头拖拽组件 const ResizableTitle = ({ onResize, width, ...restProps }) => { 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} style={{ ...restProps?.style, userSelect: 'none' }} /> </Resizable> ); }; // 带拖拽表格组件 const ResizableTable = ({ columns = [], ...props }) => { // * 列数据 const [cols, setCols] = useState(columns); const colsArray = cols.map((col, index) => { return { ...col, onHeaderCell: column => ({ width: column.width, onResize: handleResize(index) }) }; }); // todo 调整列宽 const handleResize = index => { return (_, { size }) => { const temp = [...cols]; temp[index] = { ...temp[index], width: size.width }; setCols(temp); }; }; return ( <Table components={{ header: { cell: ResizableTitle } }} columns={colsArray} {...props} /> ); }; export default ResizableTable;
components/ResizableTableModel/index.css
// components/ResizableTableModel/index.css .react-resizable-handle { position: absolute; right: -5px; bottom: 0; z-index: 1; width: 10px; height: 100%; cursor: col-resize; }
pages/home/index.jsx
// pages/home/index.jsx import React from 'react' import { Divider, Table } from 'antd' import ResizeableTableModel from '@/components/ResizeableTableModel' const dataSource = [ { _id: 1, label: '范德萨1', gender: '男' }, { _id: 2, label: '范德萨2', gender: '女' }, { _id: 3, label: '范德萨3', gender: '男' }, { _id: 4, label: '范德萨4', gender: '男' }, { _id: 5, label: '范德萨5', gender: '女' }, ] const columns = [ { title: '#', dataIndex: '_id', width: 60, ellipsis: true, }, { title: '名称', dataIndex: 'label', width: 200, ellipsis: true, }, { title: '性别', dataIndex: 'gender', width: 200, ellipsis: true, }, { title: '操作', key: 'action', width: 200, ellipsis: true, render: () => ( <a>修改</a> ), }, ]; const Layout = () => { return ( <> <Divider children="组件表格" /> <ResizeableTableModel rowKey={'_id'} columns={columns} dataSource={dataSource} /> </> ) } export default Layout
总结
要注意以下两点:
1、初始列的宽度设置
2、拖拽回调的判断赋值
制作不易,看完给小编点个赞吧!