如何更改material ui table中选定行的文本颜色

Ank*_*ita 12 css frontend reactjs material-ui

我试图在选择时更改行文本的颜色和行的背景颜色。

我能够成功更改背景颜色,但无法更改文本颜色。

<TableRow
        className={classes.tableBody}
      >

tableBody: {
    "&:focus": {
      color: "yellow !important",
      backgroundColor: "#3D85D2 !important",
    },
  },
Run Code Online (Sandbox Code Playgroud)

Rya*_*ell 15

背景颜色在 中控制TableRow。为了获得正确的特异性(在覆盖 Material-UI 样式时,您永远不需要利用“!important”),您需要利用类似于在TableRow.

颜色在 中控制TableCell,因此这是您需要控制它的级别。

对于有效的解决方案,在样式中,您将具有以下内容:

const styles = theme => ({
  tableRow: {
    "&$hover:hover": {
      backgroundColor: "blue"
    }
  },
  tableCell: {
    "$hover:hover &": {
      color: "pink"
    }
  },
  hover: {}
});
Run Code Online (Sandbox Code Playgroud)

然后在渲染中:

            <TableRow
              hover
              key={row.id}
              classes={{ hover: classes.hover }}
              className={classes.tableRow}
            >
              <TableCell
                className={classes.tableCell}
                component="th"
                scope="row"
              >
                {row.name}
              </TableCell>
Run Code Online (Sandbox Code Playgroud)

这是基于您的沙箱的工作版本:

编辑表格悬停颜色

这是一个类似的例子,但使用“selected”而不是“hover”:

https://codesandbox.io/s/llyqqwmr79

这使用以下样式:

const styles = theme => ({
  tableRow: {
    "&$selected, &$selected:hover": {
      backgroundColor: "purple"
    }
  },
  tableCell: {
    "$selected &": {
      color: "yellow"
    }
  },
  selected: {}
});
Run Code Online (Sandbox Code Playgroud)

和一些状态:

 const [selectedID, setSelectedID] = useState(null);
Run Code Online (Sandbox Code Playgroud)

并将 TableRow 渲染更改为:

            <TableRow
              hover
              key={row.id}
              onClick={() => {
                setSelectedID(row.id);
              }}
              selected={selectedID === row.id}
              classes={{ selected: classes.selected }}
              className={classes.tableRow}
            >
Run Code Online (Sandbox Code Playgroud)

Material-UI 的 v4 将包含一些更改这些更改将使覆盖样式变得更加容易(并且更容易弄清楚如何在不查看源代码的情况下成功完成)。

在Material-UI的v4中,我们可以为选中状态(“Mui-selected”)和TableCell(“MuiTableCell-root”)使用全局类名,然后我们只需要将一个类应用到TableRow:

const styles = (theme) => ({
  tableRow: {
    "&.Mui-selected, &.Mui-selected:hover": {
      backgroundColor: "purple",
      "& > .MuiTableCell-root": {
        color: "yellow"
      }
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

编辑表格悬停颜色(分叉)