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

如何使用MUI styled函数样式化MUI组件(不使用makestyles/sx)

正确的MUI原生组件样式化方案

你之前的代码错误在于将Avatar用字符串'Avatar'传入了styled函数,正确的做法是直接传入MUI组件本身,而非字符串形式的组件名。以下是修正后的实现:

import * as React from 'react';
import { styled } from '@mui/system';
import Avatar from "@mui/material/Avatar";

// 直接传入Avatar组件引用,无需加引号
const StyledAvatar = styled(Avatar)({
  color: 'darkslategray',
  backgroundColor: 'aliceblue',
  padding: 8,
  borderRadius: 4,
});

export default function BasicUsage() {
  return <StyledAvatar>SA</StyledAvatar>;
}

关键说明

  • 样式化HTML原生元素(如div、span)时,传入字符串标签名;样式化MUI组件或自定义组件时,直接传入组件引用即可。
  • 该方案完全不需要使用makeStyles或sx props,符合你的需求。
  • 若需要结合MUI主题变量,也可以写成函数形式:
    const StyledAvatar = styled(Avatar)(({ theme }) => ({
      color: theme.palette.text.primary,
      backgroundColor: theme.palette.secondary.light,
    }));
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 18:35:11