Material-UI Table/XGrid - 如何为每个单元格设置不同的颜色

ic3*_*ic3 5 emotion material-ui mui-x

当您的已知选项数量有限时,material-ui 中的单元格表的样式很好,但在事先未知的情况下我会遇到困难。

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

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

当前的解决方案如下所示(doc):

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

如何在material-ui v5/emotion(doc)中动态创建添加样式或css。就像是 :

 cellSx: (params: GridCellClassParams) =>{
    {
      backgroundColor: params.value
    }
  }),
Run Code Online (Sandbox Code Playgroud)

Pha*_*ani 0

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

动态创建“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',
    },
  },
});
Run Code Online (Sandbox Code Playgroud)