Material Icons hover效果失效,请求技术排查与解决
Material Icons hover效果不生效的解决方法
你遇到的问题核心是原生内联style属性不支持CSS伪类选择器,你写的&:hover是MUI专属的CSS-in-JS语法,直接放在style里不会被解析,所以hover效果无法触发。下面是几种可行的解决方案:
方案1:使用MUI的sx属性(推荐,适用于MUI v5+)
sx是MUI v5内置的样式方案,支持直接编写伪类语法,替换原来的style即可:
import ManageAccountsIcon from '@mui/icons-material/ManageAccounts'; import NotificationsIcon from '@mui/icons-material/Notifications'; import HelpIcon from '@mui/icons-material/Help'; const iconSx = { fontSize: "25px", color: "grey", paddingRight: "30px", paddingTop: "20px", cursor: "pointer", borderRadius: "10%", "&:hover": { color: "black" } } <HelpIcon sx={iconSx}/> <NotificationsIcon sx={iconSx}/> <ManageAccountsIcon sx={iconSx}/>
方案2:使用styled组件(MUI v5)
通过styled创建一个带样式的容器组件,包裹图标实现hover效果:
import { styled } from '@mui/material/styles'; import ManageAccountsIcon from '@mui/icons-material/ManageAccounts'; import NotificationsIcon from '@mui/icons-material/Notifications'; import HelpIcon from '@mui/icons-material/Help'; const StyledIconWrapper = styled('div')({ fontSize: "25px", color: "grey", paddingRight: "30px", paddingTop: "20px", cursor: "pointer", borderRadius: "10%", "&:hover": { color: "black" } }); // 使用时包裹图标 <StyledIconWrapper><HelpIcon /></StyledIconWrapper> <StyledIconWrapper><NotificationsIcon /></StyledIconWrapper> <StyledIconWrapper><ManageAccountsIcon /></StyledIconWrapper>
方案3:使用makeStyles(适用于MUI v4)
如果你的项目仍在使用MUI v4,可以用makeStyles生成类名绑定到图标上:
import { makeStyles } from '@material-ui/core/styles'; import ManageAccountsIcon from '@mui/icons-material/ManageAccounts'; import NotificationsIcon from '@mui/icons-material/Notifications'; import HelpIcon from '@mui/icons-material/Help'; const useStyles = makeStyles({ icon: { fontSize: "25px", color: "grey", paddingRight: "30px", paddingTop: "20px", cursor: "pointer", borderRadius: "10%", "&:hover": { color: "black" } } }); // 在组件内调用useStyles获取类名 const classes = useStyles(); <HelpIcon className={classes.icon}/> <NotificationsIcon className={classes.icon}/> <ManageAccountsIcon className={classes.icon}/>
内容的提问来源于stack exchange,提问作者murage kibicho
相关产品推荐
相关产品推荐

