更改 MUI 表的活动样式

问题描述

我有一个表格,我可以在其中对输入进行排序,就像在 mui 网站上的“排序和选择”下一样: https://material-ui.com/components/tables/

我想要的是更改选择用于排序的标题文本的颜色。我尝试了以下方法,但只能以这种方式更改背景颜色(简化代码示例):

const useStyles = makeStyles({
  active: {
    color: "yellow",backgroundColor: "yellow",},});

function Example() {
  const classes = useStyles();
  // functions for sorting etc. here left out
  return (
  <TableContainer component={Paper}>
      <Table>
          <TableHead>
              <TableRow>
               <StyledTableCell>
                    <TableSortLabel
                      active={valuetoOrderBy === "column"}
                      direction={
                        valuetoOrderBy == "column" ? orderDirection : "asc"
                      }
                      onClick={createSortHandler("column")}
                      classes={{ active: classes.active }}
                    >
                      column
                    </TableSortLabel>
                  </StyledTableCell>
                 </TableRow>
          </TableHead>
        <TableBody>
        // data that comes in the column
       </TableBody>
         </Table>
        </TableContainer>
        )}

因此,当我单击该列时,该列已排序并且标题文本的背景颜色变为黄色,但文本颜色不变。我曾尝试更改主题活动和所选颜色,但这也不起作用。

解决方法

回答 here 的问题是相同的。

问题是颜色是在 root&$active 选择器中定义的。 active 选择器仅用作“伪”选择器,如 source 中所示。

以下代码将正确覆盖这两个属性:

const useStyles = makeStyles({
  root: {
    '&$active': {
      color: "yellow",backgroundColor: "yellow",},active: {},// pseudo
});

...

<TableSortLabel
  active={valueToOrderBy === "column"}
  direction={
    valueToOrderBy == "column" ? orderDirection : "asc"
  }
  onClick={createSortHandler("column")}
  classes={{ root: classes.root,active: classes.active }}
>
  column
</TableSortLabel>

Codesandbox