如何使用MUI的makeStyles钩子实现Typography组件悬停下划线动画
实现方案
你现有代码的核心错误是伪元素的触发规则写反了:&:before:hover是要求鼠标悬停在初始宽度为0的伪元素上才会生效,自然没有任何反馈。正确逻辑是父元素被悬停时,修改其伪元素的样式,对应选择器写为&:hover::before即可。
修正后的完整可运行代码如下:
import { makeStyles } from '@material-ui/core/styles'; import Link from '@material-ui/core/Link'; import Typography from '@material-ui/core/Typography'; const useStyles = makeStyles({ link: { color: "white", position: "relative", // 移除MUI Link组件默认下划线,避免和自定义动画冲突 textDecoration: "none", "&::before": { content: "''", position: "absolute", width: "0", height: "2px", // 调整下划线和文字的间距,可根据需求修改 bottom: "-3px", left: "0", backgroundColor: "#FFF", transition: "all 0.3s ease-in-out", }, // 核心修正:父元素 hover 时修改伪元素宽度 "&:hover::before": { width: "100%" } } }); function NavButton(props){ const classes = useStyles(); return ( // 直接用MUI Link组件的href属性,无需额外嵌套a标签 <Link href={`/#${props.text}`} className={classes.link}> <Typography>{props.text}</Typography> </Link> ); }
关键知识点说明
- makeStyles的选择器语法中,
&指代当前元素的生成类名,&::before就是给当前元素添加before伪元素,&:hover::before表示当前元素被悬停时,对应的伪元素应用该段样式 - 原代码中的
visibility属性属于冗余配置,伪元素宽度为0时本身不可见,仅靠宽度变化的过渡动画就可以实现从左到右展开的效果 - MUI的Link组件原生支持href属性,直接使用可以减少不必要的DOM嵌套层级
如果你使用的是MUI v5版本,也可以用styled组件或者sx属性实现相同效果,核心的伪元素动画逻辑是通用的。
内容的提问来源于stack exchange,提问作者Joshua Reisbord
相关产品推荐
相关产品推荐

