index.tsx
2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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;