首页 > 解决方案 > Material-UI Table/XGrid - 如何为每个单元格设置不同的颜色

问题描述

当您的已知选项数量有限时,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-uiemotionmaterial-ui-x

解决方案


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

您可以利用材料 ui useStyles 钩子高级功能来创建接受道具的 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}`} />
}

你可以从这里找到文档。


推荐阅读