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

2,199 阅读1分钟

1.npm下载依赖包

npm install react-resizable --save

如果上述报错缺依赖包react-draggable还需要引入react-draggable包,并重启项目 

2.公共组件

样式

index.css

.react-resizable {    position: relative; }

.react-resizable-handle { position: absolute; right: -5px; bottom: 0; z-index: 1; width: 10px; height: 100%; cursor: col-resize;}

import React from "react";

import { Resizable } from 'react-resizable';

import "./index.css";

const ResizeableTitle = (props) => {

     const { onResize, width, ...restProps } = props;

      return (

         

             <th {...restProps} />

         

     )

   };

export default ResizeableTitle

3.父组件

import React,{useState,useEffect,useRef} from "react";

import ResizeableTitle from "../../components/Resizable/resizable"

const SystemLayout = () =>{

    const [columns,setColumns] = useState( [

      {

         title: "名称",

         dataIndex: "title",

          width:200,

         align: "center",

      },

     {

       title: "key",

       dataIndex: "key",

       width:200,

      align: "center",

    },

    {

     title: "密码",

     dataIndex: "explain",

     width:200,

     align: "center",

     }

]);  

 const components = {

    header: {

    cell: ResizeableTitle,

     },

};  

const handleResize = index => (e, { size }) => {

       const nextColumns = [...columns];

       nextColumns[index] = {

          ...nextColumns[index],

          width: size.width,

        };

          setColumns(nextColumns);

    };

  let columnse = columns.map((col, index) => ({

                 ...col,

        onHeaderCell: column => ({

             width: column.width,

             onResize: handleResize(index),

          }),

      }));

return (

      <Table

        rowKey='id'

        bordered

        components={components}

        columns={columnse}

        dataSource={data}

        scroll={{ y: 650, scrollToFirstRowOnChange: true}}

     />

     )

}

export default SystemLayout;