【问题标题】:Material-UI Table/XGrid - How to set a different color for each cellMaterial-UI Table/XGrid - 如何为每个单元格设置不同的颜色
【发布时间】:2021-08-11 07:26:10
【问题描述】:

material-ui 中单元格表的样式在已知选项数量有限的情况下很好,但在事先不知道的情况下我正在苦苦挣扎。

为了简化,想法是根据表格单元格的值设置每个单元格的背景颜色(让我们假设单元格的值实际上是颜色)。

使用 cellRenderers 是有限的(不是一个真正干净的选项)。

当前的解决方案看起来像 (doc):

 cellClassName: (params: GridCellClassParams) =>
    clsx('super-app', {
      negative: (params.value as number) < 0,
     positive: (params.value as number) > 0,
    }),

如何在 material-ui v5/emotion (doc) 中动态创建添加样式或 css。类似的东西:

 cellSx: (params: GridCellClassParams) =>{
    {
      backgroundColor: params.value
    }
  }),

【问题讨论】:

    标签: material-ui emotion material-ui-x


    【解决方案1】:

    根据您的问题,我了解到您将收到颜色名称,并且需要将这些颜色应用到存在颜色名称的单元格上。

    动态创建“clsx”方法中存在的对象。

    // let us consider that there is a key named color in the params which is received in the colums.
    
    const generateColorsObject = (color) => {
      const colorKey = color;
      const colorObject = {}
      colorObj[colorKey] = color
      return colorObj; // it's value will have something like { 'red': 'red' }
    }
    
    const columns = [
      {
        field: 'name',
        cellClassName: 'super-app-theme--cell',
      },
      {
        field: 'score',
        type: 'number',
        width: 140,
        cellClassName: (params) =>
          clsx('super-app', generateColorsObject(params.color)),
      },
    ];
    
    const useStyles = makeStyles({
      root: {
        '& .super-app.red': {
          backgroundColor: 'red', // you need to configure the background colors to the colorKey
          color: '#1a3e72',
          fontWeight: '600',
        },
        '& .super-app.blue': {
          backgroundColor: 'blue',
          color: '#1a3e72',
          fontWeight: '600',
        },
        '& .super-app.orange': {
          backgroundColor: 'orange',
          color: '#1a3e72',
          fontWeight: '600',
        },
      },
    });

    【讨论】:

      【解决方案2】:

      我认为问题归结为创建一个从收到的道具应用样式的 mui 类。

      您可以利用 Material ui useStyles hook 高级功能来创建接受道具的 mui 类,因此您可以根据需要传递一些样式细节。

      const useStyles = makeStyles({
        // style rule
        foo: props => ({
          backgroundColor: props.backgroundColor,
        }),
        bar: {
          // CSS property
          color: props => props.color,
        },
      });
      
      function MyComponent() {
        // Simulated props for the purpose of the example
        const props = { backgroundColor: 'black', color: 'white' };
        // Pass the props as the first argument of useStyles()
        const classes = useStyles(props);
      
        return <div className={`${classes.foo} ${classes.bar}`} />
      }

      你可以从here.找到文档

      【讨论】:

        猜你喜欢
        • 2020-04-08
        • 1970-01-01
        • 2020-07-01
        • 1970-01-01
        • 2016-05-04
        • 1970-01-01
        • 2017-07-10
        • 2017-02-07
        • 2021-04-08
        相关资源
        最近更新 更多