使用Material UI设置列表样式时无法修改图标颜色,如何解决?
你目前的写法存在两个问题:
- 没有给
ListItemIcon组件绑定自定义样式类,你样式里写的$icon规则没有对应的挂载对象,无法生效 - Material UI的
ListItemIcon组件自带默认的颜色样式,优先级高于从父元素ListItem继承的颜色,所以直接给父元素设color不会作用到图标上
第一步:调整JSX代码,给ListItemIcon绑定样式类
<ListItem button variant="contained" selected={selectedIndex === index} key={text} component={Link} to={url} disabled={disabled} className={classes.listItem} classes={{ selected: classes.selected, }} onClick={(e) => handleListItemClick(e, index)} > {/* 新增className绑定 */} <ListItemIcon className={classes.listItemIcon}>{icon}</ListItemIcon> <Typography variant="button"> <ListItemText primary={text} primaryTypographyProps={{ variant: "h1", style: { fontWeight: "600" }, }} className={classes.txt} /> </Typography> </ListItem>
第二步:调整样式规则,覆盖ListItemIcon默认样式
listItem: { padding: "1.5vh", color: theme.palette.background.paper, "&:hover": { backgroundColor: theme.palette.primary.main, // 父元素hover时修改图标颜色 "& .MuiListItemIcon-root": { color: theme.palette.primary.main, fill: theme.palette.primary.main, }, "& $txt": { color: theme.palette.primary.main, }, }, "&$selected": { backgroundColor: theme.palette.background.default, color: theme.palette.primary.main, // 选中状态下修改图标颜色 "& .MuiListItemIcon-root": { color: theme.palette.primary.main, fill: theme.palette.primary.main, }, "&:hover": { backgroundColor: theme.palette.background.default, }, }, "&$selectedSection": { backgroundColor: theme.palette.background.default, color: theme.palette.primary.main, // 选中分区状态下修改图标颜色 "& .MuiListItemIcon-root": { color: theme.palette.primary.main, fill: theme.palette.primary.main, }, "&:hover": { backgroundColor: theme.palette.background.default, }, }, }, // 单独定义图标初始样式 listItemIcon: { color: theme.palette.background.paper, fill: theme.palette.background.paper, }
以上写法所有颜色都直接调用theme变量,完全支持主题切换,不需要使用行内样式。
内容的提问来源于stack exchange,提问作者Shalon Machado
相关产品推荐
相关产品推荐

