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

如何仅为选中状态的MUI Switch组件设置边框样式

实现方案

你可以把原本定义在root上的边框样式挪到track节点上,利用MUI Switch已有的选中状态选择器直接修改选中时的边框样式,该方案兼容性好,无需使用新CSS特性,修改后的完整代码如下:

import * as React from "react";
import Switch from "@mui/material/Switch";
import { withStyles } from "@material-ui/core/styles";
const label = { inputProps: { "aria-label": "Switch demo" } };

const CustomSwitch = withStyles({
  root: {
    width: "40px",
    height: "20px",
    padding: "0px",
    borderRadius: "10px",
    marginRight: "8px",
    position: "relative"
  },

  colorSecondary: {
    "&.Mui-checked + .MuiSwitch-track": {
      backgroundColor: "#05756C",
      // 选中状态移除边框
      border: "none"
    },
    "&.Mui-checked": {
      color: "white"
    }
  },
  thumb: {
    position: "absolute",
    width: "12px",
    height: "12px"
  },
  track: {
    backgroundColor: "transparent",
    // 把原root的边框移到这里
    border: "1px solid #606060",
    borderRadius: "inherit",
    // 关闭track默认半透效果,保证边框颜色正常
    opacity: 1
  },
  switchBase: {
    color: "#606060",
    "&$checked": {
      // color: 'white!important',
    }
  }
})(Switch);

export default function BasicSwitches() {
  return (
    <div>
      <CustomSwitch {...label} />
    </div>
  );
}

如果你的业务不需要兼容低版本浏览器,也可以直接在root样式中使用:has()伪类实现,修改更简单:

const CustomSwitch = withStyles({
  root: {
    width: "40px",
    height: "20px",
    padding: "0px",
    borderRadius: "10px",
    marginRight: "8px",
    border: "1px solid #606060",
    position: "relative",
    // 内部存在选中元素时移除边框
    "&:has(.Mui-checked)": {
      border: "none"
    }
  },
  // 其余原有样式保持不变
})

内容的提问来源于stack exchange,提问作者Sean Liu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 20:24:03