当前位置: 首页 > 工具软件 > react-cursor > 使用案例 >

react-resizable实现antd Table组件拖动改变列宽

符渊
2023-12-01
import { Table } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { Resizable } from 'react-resizable';
import './style.css';

const ResizeableTitle = (props: any) => {
  const { onResize, width, ...restProps } = props;

  if (!width) {
    return <th {...restProps} />;
  }

  return (
    <Resizable
      width={width}
      height={0}
      onResize={onResize}
      draggableOpts={{ enableUserSelectHack: false }}
    >
      <th {...restProps} />
    </Resizable>
  );
};

const ResizeTable: React.FC<any> = (props: any) => {

  const { columns, dataSource, ...rest} = props;

  const [cols, setCols] = useState<any>(props.columns);
  const colsRef = useRef<any[]>([]);


  const components = {
    header: {
      cell: ResizeableTitle,
    },
  };  

  useEffect(() => {
    setCols(props.columns);
  }, [props.columns])
  
  const handleResize = (index: any) => (e: any, { size }: any) => {
    const nextColumns = [...cols];

    nextColumns[index] = {
      ...nextColumns[index],
      width: size.width,
    };

    setCols(nextColumns);
  };

  colsRef.current = (cols || []).map((col: any, index: any) => ({
    ...col,
    onHeaderCell: (column: any) => ({
      width: column.width,
      onResize: handleResize(index),
    }),
  }))

  return (
    <div className="components-table-resizable-column">
      <Table 
        components={components}
        columns={colsRef.current}
        dataSource={props.dataSource}
      />
    </div>
  )
}

export default ResizeTable;
/* 内容过多以...显示 */
.ellipsisText {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: block;
}
/* 显示拖拽样式 */
.components-table-resizable-column .react-resizable {
    position: relative ;
    background-clip: padding-box;
}
.components-table-resizable-column .react-resizable-handle {
    position: absolute;
    width: 10px;
    height: 100%;
    bottom: 0;
    right: -9px;
    cursor: col-resize;
    z-index: 1;
    border-left: white 1px solid;
}
 类似资料: