繁体   English   中英

如何连接材料表反应中的两个或多个字段

[英]How to concatenate two or more fields in material-table react

我正在尝试在我的材料表中创建一个“名称”列,其中连接了我的数组中的firstname, lastname ,但它每个字段只接受一个数据。

有什么建议或帮助使它成为可能吗?

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 }
/>

不需要修改传递给表的数据的另一种方法是对该字段使用自定义渲染 function。

{
  render: (client) => {
    return `${client.firstName} ${client.lastName}`;
  },
  title: 'Client',
},

您的列需要具有数据 object 中存在的field值。

因此,将您的columns object 更改为:

const columns = [
  { title: 'Name', field: 'fullName' },
  { title: 'Address', field: 'fullAddress' },
];

获得列后,您需要修改传递给组件的数据。

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}`,
};

然后,您可以将数据传递给表:

<MaterialTable columns={columns} data={newData} />

note :我在这里使用了模板文字,因为它更容易阅读 - 但上面的代码正在执行以下操作:

const newData = {
  fullName: client.firstname + ' ' + client.lastname,
  fullAddress: client.address.address1 + ', ' + client.address.address2,
};

上述答案仅在材料表中不需要搜索时才有效,如果需要搜索,则必须将“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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM