Table 数据结构
一条数据默认显示一行,一个 tr
export const dataSource = [
{
type: '黑龙江省',
data: [
{
fault: '10',
faultRate: '11.0%',
successRate: '12',
success: '13',
time: 1623394800000,
total: '14',
cost: 15,
},
{
fault: '20',
faultRate: '21%',
successRate: '22',
success: '23',
time: 1623395300000,
total: '24',
cost: 25,
},
{
faultRate: '30',
faultRate: '31%',
successRate: '32',
success: '33',
time: 1623396700000,
total: '34',
cost: 35,
},
],
},
{
type: '青海省',
data: [
{
fault: '10',
faultRate: '13%',
successRate: '13%',
success: '15',
time: 1623394800000,
total: '16',
cost: 17,
},
],
},
];
动态渲染:时间表头
点击每行,获取当前点击列的数据,思路:
- 给每个 td添加 对应的时间戳,通过时间戳去匹配数据
- dataIndex的数组用法 ```jsx import React, { memo } from ‘react’; import PropTypes from ‘prop-types’; import { Table } from ‘antd’;
const children = [ { title: ‘总量’, dataIndex: ‘total’, width: 100, }, { title: ‘成功量’, dataIndex: ‘success’, width: 100, }, { title: ‘成功率’, dataIndex: ‘successRate’, width: 100, }, { title: ‘消耗时间’, dataIndex: ‘cost’, width: 120, }, { title: ‘错误数量’, dataIndex: ‘faultRate’, width: 90, }, ];
function getColumns(dataSource) { const { data = [] } = dataSource[0];
const columns = data.map((item, i) => {
const { time } = item;
return {
title: time, // formatDate(time)
children: children.map(child => {
const { dataIndex } = child;
return {
…child,
dataIndex: [‘data’, i, dataIndex],
key: ${dataIndex}-${i}-${time}
,
onCell: () => ({ className: time }),
};
}),
}
});
columns.unshift({ title: ‘province’, dataIndex: ‘province’, width: 100, }); return columns; }
TableServiceIndex.propTypes = { value: PropTypes.object.isRequired, onChange: PropTypes.func.isRequired, };
function TableServiceIndex({ value: values, onChange }) { const { loading, dataSource } = values;
function onRow(row) { return { onClick: ev => { const { innerText, className } = ev.target; // const time = ev.target.getAttribute(‘class’); const data = row.data.find(item => item.time === className) onChange({ value: innerText, row: data }); }, } }
const attrs = { rowKey: ‘id’, size: ‘middle’, scroll: { x: 1200 }, loading, columns: getColumns(dataSource), dataSource, bordered: true, onRow, };
return
function propsEqual(prevProps, props) { const { dataSource } = prevProps.value; return dataSource === props.value.dataSource; }
export default memo(TableServiceIndex, propsEqual);
<a name="vlIFX"></a>
### columns自定义单元格属性
onCell用法:[https://ant.design/components/table-cn/](https://ant.design/components/table-cn/)<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/112859/1624432460346-10d7ed7d-b462-47a3-beb3-ab62ab3a5ae9.png#clientId=ufabf5a2f-bb04-4&from=paste&height=38&id=u6c251dd7&originHeight=114&originWidth=1474&originalType=binary&ratio=3&size=14736&status=done&style=none&taskId=u54654f0f-f656-426c-bdc7-2d2241c3bda&width=491.3333333333333)
```jsx
const columns = [
{
title: '表头',
onCell: (row, index) => {
return {
className: row.time,
};
},
}
]
dataIndex报错
原因:dataIndex相同,导致的报错,解决,用 key属性解决 dataIndex相同引起的报错