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

React中使用MUI Chip组件如何自定义选中状态的背景颜色

MUI Chip组件自定义hover、选中态背景色解决方案

问题核心原因

  • MUI内置组件的默认样式优先级高于普通自定义类名,你写的:hover伪类样式被默认规则覆盖
  • classes属性需要传入你定义的样式类名(格式为classes.xxx),直接传入颜色字符串属于无效写法
  • Chip组件本身没有内置选中状态,需要自行维护状态变量控制选中样式

可行实现方案

方案1:使用MUI原生sx属性覆写(推荐,MUI v5及以上适用)

直接通过sx属性定义样式,自动处理优先级问题,同时自行维护选中状态:

import { useState } from 'react';
import Chip from '@mui/material/Chip';
import Avatar from '@mui/material/Avatar';

function YourComponent() {
  // 维护选中状态
  const [isSelected, setIsSelected] = useState(false);

  return (
    <Chip
      avatar={<Avatar style={{ padding: '2px' }} alt="Clickable" />}
      label="Clickable"
      variant="filled"
      clickable
      onClick={() => setIsSelected(!isSelected)}
      sx={{
        height: '40px',
        width: '125px',
        fontSize: '18px',
        // hover态样式
        '&:hover': {
          backgroundColor: 'red',
        },
        // 选中态样式,优先级更高
        ...(isSelected && {
          backgroundColor: 'green',
          '&:hover': {
            backgroundColor: 'darkgreen',
          }
        })
      }}
    />
  );
}

方案2:使用自定义类名覆写

如果要沿用classes的写法,需要正确绑定样式类,同时可以加!important强制覆盖默认样式:

// 样式定义
const useStyles = makeStyles({
  tokenChip: {
    height: '40px',
    width: '125px',
    fontSize: '18px',
    '&:hover': {
      backgroundColor: 'red !important',
    }
  },
  selectedChip: {
    backgroundColor: 'green !important',
    '&:hover': {
      backgroundColor: 'darkgreen !important',
    }
  }
});

// 组件内使用
function YourComponent() {
  const classes = useStyles();
  const [isSelected, setIsSelected] = useState(false);
  return (
    <Chip
      avatar={<Avatar style={{ padding: '2px' }} alt="Clickable" />}
      label="Clickable"
      variant="filled"
      clickable
      onClick={() => setIsSelected(!isSelected)}
      className={`${classes.tokenChip} ${isSelected ? classes.selectedChip : ''}`}
    />
  );
}

内容的提问来源于stack exchange,提问作者Kenny Quach

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 03:45:03