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

如何在不使用sx props的情况下为Material UI组件添加Hover效果?

不使用sx props为Material-UI Box添加Hover效果

以下是两种无需依赖sx props的实现方案:

方法1:使用MUI的styled API

这是Material-UI推荐的样式方案,能无缝集成主题变量,风格统一。你可以先封装一个带hover效果的自定义Box组件,再直接复用:

import React from 'react'
import { Box, styled } from '@mui/material'
import { MuiSelect } from './MuiSelect'

// 封装带hover效果的自定义Box
const HoverBox = styled(Box)(({ theme }) => ({
  display: 'flex',
  height: '100px',
  width: '768px',
  backgroundColor: theme.palette.success.light,
  padding: theme.spacing(2),
  '&:hover': {
    backgroundColor: theme.palette.success.main, // hover时切换为success主色
    transition: 'background-color 0.3s ease' // 可选:添加平滑过渡动画
  }
}))

export const MuiLayout = () => {
  return (
    <>
      <Box 
        sx={{
          backgroundColor: 'primary.main',
          color: 'white',
          height: '100px',
          width: '50%',
          padding: '16px',
          '&:hover': {
            backgroundColor: 'primary.light',
          },
        }}>
        <MuiSelect />
      </Box>
      {/* 使用自定义的HoverBox组件 */}
      <HoverBox>
      </HoverBox>
    </>
  )
}

方法2:使用自定义CSS类

如果你更习惯传统CSS写法,可通过className绑定自定义样式:

先在单独的CSS文件(比如MuiLayout.css)中定义样式:

.custom-hover-box {
  display: flex;
  height: 100px;
  width: 768px;
  background-color: var(--mui-palette-success-light);
  padding: 16px; /* 对应MUI的p={2} */
  transition: background-color 0.3s ease;
}

.custom-hover-box:hover {
  background-color: var(--mui-palette-success-main);
}

然后在组件中引入并使用:

import React from 'react'
import { Box } from '@mui/material'
import { MuiSelect } from './MuiSelect'
import './MuiLayout.css' // 引入自定义CSS

export const MuiLayout = () => {
  return (
    <>
      <Box 
        sx={{
          backgroundColor: 'primary.main',
          color: 'white',
          height: '100px',
          width: '50%',
          padding: '16px',
          '&:hover': {
            backgroundColor: 'primary.light',
          },
        }}>
        <MuiSelect />
      </Box>
      <Box 
        className="custom-hover-box"
      >
      </Box>
    </>
  )
}

注:MUI默认会将主题变量注入全局CSS变量,因此可以直接在自定义CSS中使用--mui-palette-*系列变量。

内容的提问来源于stack exchange,提问作者poshan baral

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 21:07:04