我试图在选择时更改行文本的颜色和行的背景颜色。
我能够成功更改背景颜色,但我无法更改文本颜色。
<TableRow
className={classes.tableBody}
>
tableBody: {
"&:focus": {
color: "yellow !important",
backgroundColor: "#3D85D2 !important",
},
},
背景颜色在TableRow
中控制。为了获得正确的特异性(在覆盖Material-UI样式时,您不需要利用“!important”),您需要利用类似于TableRow
中所做的“悬停”类。
颜色在TableCell
中控制,因此这是您需要控制它的级别。
对于工作解决方案,在样式中你会有类似的东西:
const styles = theme => ({
tableRow: {
"&$hover:hover": {
backgroundColor: "blue"
}
},
tableCell: {
"$hover:hover &": {
color: "pink"
}
},
hover: {}
});
然后在渲染中:
<TableRow
hover
key={row.id}
classes={{ hover: classes.hover }}
className={classes.tableRow}
>
<TableCell
className={classes.tableCell}
component="th"
scope="row"
>
{row.name}
</TableCell>
这是一个基于沙盒的工作版本:
这是一个类似的例子,但使用“选择”而不是“悬停”:
https://codesandbox.io/s/llyqqwmr79
这使用以下样式:
const styles = theme => ({
tableRow: {
"&$selected, &$selected:hover": {
backgroundColor: "purple"
}
},
tableCell: {
"$selected &": {
color: "yellow"
}
},
selected: {}
});
和一些国家:
const [selectedID, setSelectedID] = useState(null);
并将TableRow渲染更改为:
<TableRow
hover
key={row.id}
onClick={() => {
setSelectedID(row.id);
}}
selected={selectedID === row.id}
classes={{ selected: classes.selected }}
className={classes.tableRow}
>
Material-UI的v4将包含some changes,它应该使覆盖样式变得更加容易(并且更容易找出如何在不查看源代码的情况下成功完成)。