index.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 === 0) {
    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 {
    return '';
  }
};

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

  const sex: Record<string, string> = {
    '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;
    const newColumns = columns?.map((item: any) => {
      // 处理attr
      if (item.attr) {
        handleAttr(item);
      }
      // 设置ellipsis
      item.ellipsis = true;
      // 计算scroll
      if (item.width) calculateScroll += item.width;

      return item;
    });

    setTableColumns(newColumns);
    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;