如何解决我如何在ReactJS的materialui表中明智地添加数据列
如何在reactjs的materialui表中明智地添加数据列。例如,我有100个分支机构,我想要带有分支名称的表标题,并且该列应包含员工的姓名。 因此应该有100个表头。 Array = [{branchname:'String',Employees []}]
解决方法
Ciao,好吧,您必须处理一下数据结构,因为Materual UI Table
接受按行而不是按列组织的数据。
假设您的数据如下:
const branchEmployees = [
{ branchname: "branch1",employees: ["e1","e2","e3"] },{ branchname: "branch2",employees: ["e4","e5","e6"] },{ branchname: "branch3",employees: ["e7","e8","e9"] },{ branchname: "branch4",employees: ["e10","e11","e12"] },{ branchname: "branch5",employees: ["e13","e14","e15"] }
];
因此,首先创建一个具有所有分支名称的数组。像这样:
let bEmp = [];
branchEmployees.forEach((el) => {
bEmp.push(el.branchname);
});
然后,我们必须以这种方式还原员工数据:
发件人:
employees: ["e1","e3"]
employees: ["e4","e6"]
employees: ["e7","e9"]
employees: ["e10","e12"]
employees: ["e13","e15"]
收件人:
employees: ["e1","e4","e7","e10","e13"]
employees: ["e2","e14"]
employees: ["e3","e6","e9","e12","e15"]
要实现此目的,您可以定义一个代表每个分支机构最大员工人数的const,然后进行嵌套的for loop
进行上述转换。像这样:
const NUMBER_OF_EMPLOYEES_PER_BRANCH = 3; // this is the max number of employees per branch
let arrLp = [];
for (let j = 0; j < NUMBER_OF_EMPLOYEES_PER_BRANCH; j++) {
let arrayLookup = [];
for (let i = 0; i < branchEmployees.length; i++) {
arrayLookup.push(branchEmployees[i].employees[j]);
}
arrLp.push(arrayLookup);
}
因此,现在您拥有bEmp
,其中包含所有分支机构名称; arrLp
,其中包含每行所有员工。
现在只需要创建2个状态变量来存储这些值并在Table
组件上使用它们即可。
Here一个代码框示例。
注意:如果每个分支机构的员工人数不同,此解决方案也可以使用。只需将NUMBER_OF_EMPLOYEES_PER_BRANCH
设置为分支机构可以拥有的最大雇员数即可:)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。