You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

最新版MUI的Link组件hover效果失效、自定义CSS样式不生效问题

样式不生效的核心原因
  • 行内样式优先级高于类选择器:你给所有Link组件添加了行内style={{color: 'black'}},类选择器定义的hover颜色优先级低于行内样式,无法覆盖生效。
  • 选择器标识符错误:样式代码中使用了HTML转义字符&代替CSS-in-JS所需的父选择器标识符&,导致选择器匹配逻辑失效,无法命中目标元素。
  • 样式方案已废弃且优先级不足:MUI v5 中@mui/styles提供的makeStyles属于废弃方案,默认样式优先级低于MUI组件内置样式,未手动调整注入顺序的情况下自定义样式会被内置样式覆盖。
  • 部分样式类未定义:代码中引用的classes.Toolbar、classes.ButtonItems没有在makeStyles中定义对应规则,对应位置样式自然不生效。
  • 缺少必要上下文依赖:@mui/styles的API需要在ThemeProvider包裹的组件上下文中才能正常运行,若应用根节点未包裹ThemeProvider也会导致样式失效。
修复方案
  1. 移除Link组件上的行内style={{color: 'black'}},将默认颜色统一写入自定义样式规则中
  2. 把样式代码中所有&替换为原生&
  3. 推荐替换为MUI v5 官方推荐的styled API 或sx属性定义样式,避免优先级问题
  4. 补全缺失的样式类规则,或移除未定义的className引用
  5. 确保应用根组件已用ThemeProvider包裹
修复后参考代码
import {Link, Button, AppBar, Toolbar, ThemeProvider, createTheme} from '@mui/material';
import {styled} from '@mui/material/styles';

// 用styled定义自定义组件
const StyledLink = styled(Link)(({theme}) => ({
  color: 'black',
  '&:hover': {
    color: '#E0475B'
  }
}));

const StyledButton = styled(Button)(({theme}) => ({
  backgroundColor: '#E0475B',
  color: 'white',
  fontSize: '1.5rem'
}));

const MenuItemsWrapper = styled('div')(({theme}) => ({
  '& li': {
    display: 'inline',
    marginRight: '2rem',
  }
}));

const ButtonItemsWrapper = styled('div')(({theme}) => ({
  '& li': {
    display: 'inline',
    marginLeft: '1rem'
  }
}));

const theme = createTheme();

const HomeMenu = () => {
  return ( 
    <ThemeProvider theme={theme}>
      <div className="Body">
        <AppBar style={{backgroundColor: 'white'}}>
          <Toolbar>
            <MenuItemsWrapper>
              <ul>
                <li>
                  <StyledLink href='/' underline='none'>Home</StyledLink>
                </li>
                <li>
                  <StyledLink href='/' underline='none'>About Us</StyledLink>
                </li>
                <li>
                  <StyledLink href='/' underline='none'>Our Mission</StyledLink>
                </li>
                <li>
                  <StyledLink href='/' underline='none'>Contact Us</StyledLink>
                </li>
              </ul>
            </MenuItemsWrapper>
            <ButtonItemsWrapper>
              <ul>
                <li><StyledButton variant='contained'>Sign Up</StyledButton></li>
                <li><StyledButton variant='contained'>Log In</StyledButton></li>
              </ul>
            </ButtonItemsWrapper>
          </Toolbar>
        </AppBar>
      </div>
    </ThemeProvider>
  );
}
 
export default HomeMenu;

内容的提问来源于stack exchange,提问作者Mohammad Faateh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 10:54:06