React.js中移除MUI卡片与按钮默认悬停背景效果的方法咨询
解决MUI卡片与按钮的悬停背景禁用问题
一、为什么你的自定义CSS没生效?
background-color: none是无效写法,CSS中背景色不能设为none,正确值为transparent(透明)或inherit(继承父元素);- MUI通过CSS-in-JS生成样式,优先级高于普通全局CSS,仅靠
!important可能无法覆盖默认样式; - 若你用了
CardActionArea组件,卡片的悬停效果实际来自该组件,而非Card本身,针对Card的样式自然无效。
二、禁用MUI卡片的悬停效果
根据你的使用场景,选择以下方法:
1. 直接在组件上用sx属性(推荐,局部生效)
- 若悬停效果来自
Card本身:
import Card from '@mui/material/Card'; <Card sx={{ '&:hover': { backgroundColor: 'transparent', transition: 'none' } }}> {/* 卡片内容 */} </Card>
- 若悬停效果来自
CardActionArea:
import Card from '@mui/material/Card'; import CardActionArea from '@mui/material/CardActionArea'; <Card> <CardActionArea sx={{ '&:hover': { backgroundColor: 'transparent' } }}> {/* 卡片内容 */} </CardActionArea> </Card>
2. 用styled组件封装(适合复用)
import { styled } from '@mui/material/styles'; import Card from '@mui/material/Card'; const NoHoverCard = styled(Card)` &:hover { background-color: transparent !important; transition: none !important; } `; // 使用自定义卡片 <NoHoverCard>...</NoHoverCard>
3. 全局主题配置(全局禁用所有卡片悬停)
import { createTheme, ThemeProvider } from '@mui/material/styles'; const theme = createTheme({ components: { MuiCard: { styleOverrides: { root: { '&:hover': { backgroundColor: 'transparent', transition: 'none' } } } }, // 若需禁用CardActionArea的悬停,添加以下配置 MuiCardActionArea: { styleOverrides: { root: { '&:hover': { backgroundColor: 'transparent' } } } } } }); // 用ThemeProvider包裹整个应用 <ThemeProvider theme={theme}> {/* 应用内容 */} </ThemeProvider>
三、禁用MUI按钮的悬停背景效果
1. 局部自定义(sx属性)
- 针对普通按钮:
import Button from '@mui/material/Button'; <Button sx={{ '&:hover': { backgroundColor: 'transparent', boxShadow: 'none' } }}> 普通按钮 </Button>
- 针对
contained变体按钮(需保留原背景色时):
<Button variant="contained" sx={{ '&:hover': { backgroundColor: (theme) => theme.palette.primary.main, boxShadow: 'none' } }} > 填充按钮 </Button>
2. 封装styled组件(复用场景)
import { styled } from '@mui/material/styles'; import Button from '@mui/material/Button'; const NoHoverButton = styled(Button)` &:hover { background-color: transparent !important; box-shadow: none !important; } `; // 使用自定义按钮 <NoHoverButton variant="contained">无悬停按钮</NoHoverButton>
3. 全局主题配置(全局禁用按钮悬停)
const theme = createTheme({ components: { MuiButton: { styleOverrides: { root: { '&:hover': { backgroundColor: 'transparent', boxShadow: 'none' } }, // 仅针对contained变体 contained: { '&:hover': { backgroundColor: 'inherit', boxShadow: 'none' } } } } } });
内容的提问来源于stack exchange,提问作者Muhammad Tayyab
相关产品推荐
相关产品推荐

