React中Material UI给嵌套Link的Box组件加hover效果失败求助
解决Material UI中Link内部组件hover效果不显示的问题
你的Box hover样式没生效,核心原因是Card组件自带默认背景色,完全覆盖了Box的背景,导致hover时Box的样式无法显现;另外Box的尺寸由Card决定,本身没有独立的可视区域,hover触发范围也被Card限制。
下面是几个实用的解决办法:
方案一:直接给Card添加hover样式
把hover逻辑移到Card的sx属性中,直接作用在可见的Card容器上,效果最直观:
import { Avatar, Box, Card, CardHeader } from "@mui/material"; import { Link } from "react-router-dom"; function UserItem(props) { return ( <> <Link to="" style={{ textDecoration: "none" }}> <Box sx={{ display: "flex", justifyContent: "center" }}> <Card sx={{ width: 300, transition: "all 0.3s ease", // 可选,添加平滑过渡动画 "&:hover": { backgroundColor: "black", color: "white", } }} > <CardHeader avatar={ <Avatar alt="Avatar" src={props.item.image} sx={{ width: 56, height: 56 }} /> } title={props.item.id} subheader={props.item.name} /> </Card> </Box> </Link> </> ); } export default UserItem;
方案二:让Box完全包裹Card并显示hover效果
调整Box的尺寸和Card的背景,让Box的hover样式能透过Card显现:
import { Avatar, Box, Card, CardHeader } from "@mui/material"; import { Link } from "react-router-dom"; function UserItem(props) { return ( <> <Link to="" style={{ textDecoration: "none" }}> <Box sx={{ display: "flex", justifyContent: "center", width: 300, padding: 1, // 给Box加内边距,扩大hover触发区域 borderRadius: 2, // 和Card圆角匹配 "&:hover": { backgroundColor: "black", }, }} > <Card sx={{ width: "100%", backgroundColor: "transparent", // 让Card背景透明 color: "inherit", // 继承Box的文字颜色 transition: "all 0.3s ease" }} > <CardHeader avatar={ <Avatar alt="Avatar" src={props.item.image} sx={{ width: 56, height: 56 }} /> } title={props.item.id} subheader={props.item.name} /> </Card> </Box> </Link> </> ); } export default UserItem;
方案三:给整个Link添加hover样式
用Material UI的styled封装Link,让整个Link区域都能触发hover效果:
import { Avatar, Box, Card, CardHeader, styled } from "@mui/material"; import { Link } from "react-router-dom"; // 封装带hover样式的Link const StyledLink = styled(Link)(({ theme }) => ({ textDecoration: "none", display: "flex", justifyContent: "center", width: 300, padding: theme.spacing(1), borderRadius: theme.shape.borderRadius * 2, "&:hover": { backgroundColor: "black", }, })); function UserItem(props) { return ( <StyledLink to=""> <Card sx={{ width: "100%", backgroundColor: "transparent", color: "white", // 直接设置hover时的文字颜色 }} > <CardHeader avatar={ <Avatar alt="Avatar" src={props.item.image} sx={{ width: 56, height: 56 }} /> } title={props.item.id} subheader={props.item.name} /> </Card> </StyledLink> ); } export default UserItem;
内容的提问来源于stack exchange,提问作者Rigved Telang
相关产品推荐
相关产品推荐

