在Ant Design
中,如果我们要使用table
,可以到官网文档中查看详细的例子。
但是在例子中,你会发现类似以下的数据结构:
const columns = [{
title: 'Name',
dataIndex: 'name',
key: 'name',
render: text => (<a href="javascript:;">{text}</a>),
}, {
title: 'Age',
dataIndex: 'age',
key: 'age',
}, {
title: 'Address',
dataIndex: 'address',
key: 'address',
}, {
title: 'Tags',
key: 'tags',
dataIndex: 'tags',
render: tags => (
<span>
{tags.map(tag => <Tag color="blue" key={tag}>{tag}</Tag>)}
</span>
),
}, {
title: 'Action',
key: 'action',
render: (text, record) => (
<span>
<a href="javascript:;">Invite {record.name}</a>
<Divider type="vertical" />
<a href="javascript:;">Delete</a>
</span>
),
}];
可以看到,数组的object
中有key
,dataIndex
,title
,render
这些keys
。
title
以及render
都好理解,title
指的是thead
中每个th
的显示字段,render
指的是用什么样的方式来显示数据(通常为一个返回ReactNode
的函数)。
那么dataIndex
指的是什么意思呢?
我们先来看一下官方文档怎么说:
Property | Description | Type |
---|---|---|
dataIndex | Display field of the data record, could be set like a.b.c、a[0].b.c[1] 列数据在数据项中对应的 key,支持 a.b.c、a[0].b.c[1] 的嵌套写法 | string |
由于英文文档解释的很潦草,这里我把中文文档中的解释也加了进去。
我们看到,假设我们dataIndex
为name
,那么我们在table
的dataSource
中指定的每一个数据中,都必须包含有name
为key
的对象,而显示出的数据就是相应key
对应的数据:
const data = [{
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: 'Sidney No. 1 Lake Park',
tags: ['cool', 'teacher'],
}];
假设我们的数据结构更为复杂一些,例如name: {firstname: 'Eagle', lastname: 'Luo'}
,那么我们需要将dataIndex
改为name.firstname
或name.lastname
来获取下一层级的数据。
结合以上例子来看,dataIndex
的含义就比较明确了。需要注意的一点,如果我们已经使用了唯一的dataIndex
,那么我们就不再需要给每个column
加上key
了。