创建字典
//模拟后端返回的数据
export const userTable = [
{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park',
tags: ['nice', 'developer'],
},
{
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park',
tags: ['loser'],
},
{
key: '3',
name: 'Joe Black',
age: 32,
address: 'Sydney No. 1 Lake Park',
tags: ['cool', 'teacher'],
},
]
//定义表头文字,需要和返回数据的键名一样
export const DataTitle = [
'name', 'age', 'address', 'tags'
]
export const infoTable = [
{
key: '1',
userName: 'John Brown',
height: 160,
info: 'New York No. 1 Lake Park',
love: ['nice', 'developer'],
sex:"男"
},
{
key: '2',
userName: 'Jim Green',
height: 142,
info: 'London No. 1 Lake Park',
love: ['loser'],
sex:'男'
},
{
key: '3',
userName: 'Joe Black',
height: 232,
info: 'Sydney No. 1 Lake Park',
love: ['cool', 'teacher'],
sex:'女'
},
]
export const infoTitle = [
'userName', 'height', 'info', 'love'
]
import React, { useState } from 'react'
import TableSon from './TableSon'
import { Button, Space, Table, Tag } from 'antd';
import {userTable,DataTitle,infoTable,infoTitle} from '../../config/table'
export default function MyTable() {
const renderData = (data, DataTitle) => {
let lable = []
for (let i = 0; i < data.length; i++) {
lable = Object.keys(data[i])
}
let obj = lable.map(item => {
for (let k = 0; k < DataTitle.length; k++) {
return {
title: DataTitle[k],
dataIndex: item,
key: item
}
}
})
for (let i = 0; i < DataTitle.length; i++) {
obj[i + 1].title = DataTitle[i]
}
obj.splice(0, 1)
let columns = [
...obj,
{
title: 'Action',
key: 'action',
render: (_, record) => (
<Space size="middle">
<Button>删除</Button>
</Space>
),
},
]
return columns
}
const columns = renderData(userTable, DataTitle)
const columns2 = renderData(infoTable, infoTitle)
const myProps = {
userTable:userTable,
columns:columns
}
const myProps2={
userTable:infoTable,
columns:columns2
}
return (
<div>
<TableSon {...myProps}></TableSon>
<TableSon {...myProps2}></TableSon>
</div>
)
}
//子组件 接受props
import React from 'react'
import { Button, Space, Table, Tag } from 'antd';
export default function MyTable(props) {
const {userTable,columns} = props
return (
<div>
<Table columns={columns} dataSource={userTable} />
</div>
)
}