[英]How to concatenate two or more fields in material-table react
I'm trying to create a "Name" column in my material-table with concatenated firstname, lastname
from my array, but It only accepts one data per field.我正在尝试在我的材料表中创建一个“名称”列,其中连接了我的数组中的firstname, lastname
,但它每个字段只接受一个数据。
Any suggestion or help to make it possible?有什么建议或帮助使它成为可能吗?
const client = {
firstname: "Tracy",
lastname: "Santos",
address: {
address1: "Manila",
address2: "Philippines",
}
}
const columns = [
{ title: 'Name', field: 'client.firstname' + ' ' + 'client.lastname' },
{ title: 'Address', field: 'client.address.address1' + ' ' + 'client.address.address2' },
]
<MaterialTable
column={ columns }
data={ client }
/>
An alternate approach that doesn't require modifying the data you pass to the table would be to use a custom render function for that field.不需要修改传递给表的数据的另一种方法是对该字段使用自定义渲染 function。
{
render: (client) => {
return `${client.firstName} ${client.lastName}`;
},
title: 'Client',
},
Your columns need to have a field
value that exists in the data object.您的列需要具有数据 object 中存在的field
值。
So, change your columns
object to be:因此,将您的columns
object 更改为:
const columns = [
{ title: 'Name', field: 'fullName' },
{ title: 'Address', field: 'fullAddress' },
];
Once you have the columns, you need to modify the data you pass into the component.获得列后,您需要修改传递给组件的数据。
const client = {
firstname: 'Tracy',
lastname: 'Santos',
address: {
address1: 'Manila',
address2: 'Philippines',
}
}
// Create the new object
const newData = {
fullName: `${client.firstname} ${client.lastname}`,
fullAddress: `${client.address.address1}, ${client.address.address2}`,
};
Then, you can pass the data to the table:然后,您可以将数据传递给表:
<MaterialTable columns={columns} data={newData} />
note
: I've used Template Literals here, because it's a little easier to read - but the code above is doing the following: note
:我在这里使用了模板文字,因为它更容易阅读 - 但上面的代码正在执行以下操作:
const newData = {
fullName: client.firstname + ' ' + client.lastname,
fullAddress: client.address.address1 + ', ' + client.address.address2,
};
The above answers will only work if there is no search required in the material-table, if the search is required then you will have to add "customFilterAndSearch" to the answer as below-上述答案仅在材料表中不需要搜索时才有效,如果需要搜索,则必须将“customFilterAndSearch”添加到答案中,如下所示 -
const columns = [
{
title: 'Name',
render: client => `${client.firstname} ${client.lastname}`,
customFilterAndSearch: (term, client) => (client.firstname.toLowerCase() + ' ' + client.lastname.toLowerCase()).indexOf(term.toLowerCase()) !== -1
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.