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

如何使用MUI的styled函数根据props实现组件的不同样式变体

实现方案

你可以直接在styled的样式回调函数中解构出variant prop,根据不同的variant值返回对应的样式规则即可,variant是MUI Button原生支持的属性,不需要额外处理prop透传。

完整实现代码如下:

import { styled } from '@mui/material/styles';
import Button from '@mui/material/Button';

const RemoveButton = styled(Button)(({ theme, variant }) => ({
  // variant为contained时的红色样式
  ...(variant === 'contained' && {
    backgroundColor: 'red',
    '&:hover': {
      backgroundColor: 'darkred',
    }
  }),
  // variant为outlined时的蓝色样式
  ...(variant === 'outlined' && {
    borderColor: 'blue',
    color: 'blue',
    '&:hover': {
      borderColor: 'darkblue',
      color: 'darkblue',
    }
  }),
  // 其他通用样式可以放在此处
  borderRadius: 4,
}));

function App() {
  return (
    <>
      <RemoveButton variant="contained">Contained红色按钮</RemoveButton>
      <RemoveButton variant="outlined">Outlined蓝色按钮</RemoveButton>
    </>
  );
}

export default App;

扩展说明

如果你后续需要使用自定义的非原生props控制样式(比如自定义的isDanger属性),可以通过shouldForwardProp配置过滤不需要传递到DOM的属性,避免浏览器控制台抛出未知属性的警告,示例如下:

const RemoveButton = styled(Button, {
  // 配置不需要透传到DOM的自定义prop
  shouldForwardProp: (prop) => prop !== 'isDanger',
})(({ theme, isDanger }) => ({
  backgroundColor: isDanger ? 'red' : 'lightgreen',
}));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:36:07