table.tsx 2.4 KB
import { Table } from 'antd';
import type { TableProps } from 'antd';
import React, { useEffect, useState } from 'react';
import moment from 'moment';

import s from './index.less';

export interface tableProps extends TableProps<Record<string, number>> {
  tableHeader?: React.ReactNode;
}

export const dealNumber = (val: number) => {
  if (val && val != null) {
    let money = String(val);
    let left = money.split('.')[0],
      right = money.split('.')[1];
    right = right ? (right.length >= 2 ? '.' + right.substr(0, 2) : '.' + right + '0') : '.00';
    let temp: any = left
      .split('')
      .reverse()
      .join('')
      .match(/(\d{1,3})/g); //  将字符串顺序反转  :字符串-->数组 --> 顺序反转-->字符串
    return (Number(money) < 0 ? '-' : '') + temp.join(',').split('').reverse().join('') + right;
  } else if (val === 0) {
    return '0.00';
  } else {
    return '';
  }
};

const TableWrap: React.FC<tableProps> = (props) => {
  const { tableHeader, columns, scroll } = props;
  const [newScroll, setNewScroll] = useState<any>(0);
  const [tableColumns, setTableColumns] = useState<any>([]);

  const sex = {
    '1': '男',
    '2': '女',
  };

  const handleAttr = (item: any) => {
    const data: Record<string, any> = {
      date: (text: any) => moment(text).format(item.formatDate || 'YYYY/MM/DD'),
      unix: (text: any) => moment(text * 1000).format(item.formatDate || 'YYYY/MM/DD'),
      decimal: (text: any) => text.toFixed(2),
      money: (text: any) => dealNumber(text),
      sex: (text: keyof typeof sex) => sex[text] || '',
    };

    if (data[item.attr]) item.render = data[item.attr];
  };

  useEffect(() => {
    let calculateScroll = 0;
    columns?.map((item: any) => {
      // 处理attr
      if (item.attr) {
        handleAttr(item);
      }
      // 设置ellipsis
      item.ellipsis = true;
      // 计算scroll
      if (item.width) calculateScroll += item.width;
    });

    setTableColumns(columns);
    setNewScroll(calculateScroll);
  }, [columns]);

  return (
    <div className={s.table_components}>
      {tableHeader && <div className={s.table_header}>{tableHeader}</div>}
      <Table
        className={s.table}
        pagination={false}
        rowKey={(row) => row.id as unknown as string}
        scroll={scroll || { x: newScroll }}
        dataSource={props.dataSource || []}
        columns={tableColumns}
        {...props}
      />
    </div>
  );
};

export default TableWrap;