我有一些像这样传入的 Prop 数据
columns={
[
{
name: "Fund Name",
width: "40%"
},
{
name: "Review Date",
width: "20%"
},
{
name: "Company Debt",
width: "20%"
},
{
name: "Alerts",
width: "10%"
}
];
}
我需要它看起来像这样......
const localTheme = {
overrides: {
MUIDataTableHeadCell: {
root: {
"&:nth-child(1)": {
width: "40%"
},
"&:nth-child(2)": {
width: "20%"
},
"&:nth-child(3)": {
width: "20%"
},
"&:nth-child(4)": {
width: "10%"
},
"&:nth-child(5)": {
width: "10%"
}
}
}
}
}
我正在尝试这个...
let rowWidths = this.props.columns.map((item, key) => ({
"&:nth-child(+key+)": {
width: item.width
}
}));
const localTheme = {
overrides: {
MUIDataTableHeadCell: {
root: {
rowWidths
}
}
}
}
但这显然行不通。有人可以帮忙吗?
谢谢
最佳答案
您可以利用 Object.assign、扩展语法和字符串文字来获得所需的结果
let columns=[
{
name: "Fund Name",
width: "40%"
}, {
name: "Review Date",
width: "20%"
}, {
name: "Company Debt",
width: "20%"
}, {
name: "Alerts",
width: "10%",
}]
let rowWidths = columns.map((item, key) =>
({
[`&:nth-child(${key})`]: {
width: item.width
}
})
);
const localTheme = {
overrides: {
MUIDataTableHeadCell: {
root: Object.assign({}, ...rowWidths)
}
}
}
console.log(localTheme, rowWidths);
关于javascript - 如何在 React 中使用映射从数组创建 Material-UI 嵌套样式对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60923904/