如何在React中使用map从数组创建Material-UI嵌套样式对象 [英] How to create Material-UI nested style object from array using map in React

查看:320
本文介绍了如何在React中使用map从数组创建Material-UI嵌套样式对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些像这样传递的道具数据

I have some prop data that gets passed in like this

columns={
  [
    {
      name: "Fund Name",
      width: "40%"
    },
    {
      name: "Review Date",
      width: "20%"
    },
    {
      name: "Company Debt",
      width: "20%"
    },
    {
      name: "Alerts",
      width: "10%"
    }
  ];
}

我需要它看起来像这样...

I need it to look like this...

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

但这显然行不通.有人可以帮忙吗.

But this obviously doesn't work. Can someone please help.

谢谢

推荐答案

您可以使用Object.assign,扩展语法和字符串文字以获得所需的结果

You can make use of Object.assign, spread syntax and the string literals to get the desired result

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);

这篇关于如何在React中使用map从数组创建Material-UI嵌套样式对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆