newTable.tsx 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { Table, TableProps, Tag } from "antd"
  2. import React, { useContext, useEffect, useRef, useState } from "react"
  3. import { DispatchContext } from ".";
  4. import { Resizable } from "react-resizable";
  5. import './index.less'
  6. const ResizableHeader = (props: { [x: string]: any; onResize: any; width: any }) => {
  7. const { onResize, width, ...restProps } = props;
  8. if (!width) {
  9. return <th {...restProps} />
  10. }
  11. return <Resizable width={width} height={0} onResize={onResize} draggableOpts={{ enableUserSelectHack: false }}>
  12. <th {...restProps} />
  13. </Resizable>
  14. }
  15. const NewTable: React.FC<TableProps<any>> = ({ columns, pagination, ...props }) => {
  16. /************************************/
  17. const { total, page: current, pageSize, onPaginationChange, handelResize } = useContext(DispatchContext)!;
  18. let ww = document.body.clientWidth < 415
  19. const colsRef = useRef<any[]>([])
  20. const [cols, setCols] = useState<any>(columns)
  21. /************************************/
  22. const components = {
  23. header: {
  24. cell: ResizableHeader
  25. }
  26. }
  27. useEffect(() => {
  28. setCols(columns)
  29. }, [columns])
  30. const handleResize = (index: any) => (e: any, { size }: any) => {
  31. const nextColumns = [...cols]
  32. nextColumns[index] = {
  33. ...nextColumns[index],
  34. width: size.width
  35. }
  36. setCols(nextColumns)
  37. handelResize && handelResize(nextColumns)
  38. }
  39. colsRef.current = (cols || []).map((col: any, index: any) => ({
  40. ...col,
  41. onHeaderCell: (column: any) => ({
  42. width: column.width,
  43. onResize: handleResize(index)
  44. })
  45. }))
  46. return <div className='components-table-resizable-column'>
  47. <Table
  48. rowKey={(a: any) => (JSON.stringify(a?.id) || JSON.stringify(a?.key))}
  49. pagination={pagination ? {
  50. size: 'small',
  51. total,//总共多少条数据,服务器给,设置后分页自动计算页数
  52. current,//当前页数,需state控制配合翻页
  53. pageSize,
  54. defaultCurrent: 1,//默认初始的当前页数
  55. defaultPageSize: 20,//默认初始的每页条数
  56. pageSizeOptions: ['10', '20', '30', '40', '50', '60', '70', '80', '90', '100'],
  57. showTotal: (total) => <Tag color="cyan">总共{total}数据</Tag>,
  58. showSizeChanger: true, //手动开启条数筛选器,默认超过50条开启
  59. onChange: onPaginationChange, //点击页码或条数筛选时触发获取当前页数和每页条数
  60. simple: ww ? true : false,//开启简单分页
  61. showLessItems: true
  62. } : false}
  63. components={components}
  64. columns={colsRef?.current}
  65. {...props}
  66. />
  67. </div>
  68. }
  69. export default React.memo(NewTable)