材质UI表/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
}
}),

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

为了动态地创建存在于";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',
},
},
});

我认为这归结为创建一个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}`} />
}

你可以在这里找到医生。

为了解决这个问题,我使用了cellClassName并使用函数更改了类。这是我的工作代码:

// Based on the value of the cell the class will be applied.
const applyCellColour = (value: boolean) => (value ? 'notApprovedCell' : 'approvedCell'); 
// In the columns array in the cellClassName:
const columns: GridColDef[] = [
{
field: 'Approval',
headerName: 'Approval',
headerAlign: 'center',
align: 'center',
cellClassName: params => applyCellColour(params),
},
]    

// CSS
.approvedCell {
background-color: 'green';
}
.notApprovedCell {
background-color: 'red';
}

最新更新