如何在MUI 5的@mui/styled-engine-sc中使用Theme与Props
解决@mui/styled-engine-sc中访问主题与Props的问题
@mui/styled-engine-sc的styled方法完全支持在样式中访问MUI主题和组件Props,同时保留组件选择器功能,你的写法存在语法错误,以下是正确实现方式:
1. 模板字符串语法(推荐,保留组件选择器)
在模板字符串中通过${}嵌入函数,解构获取theme和自定义props,TypeScript下需显式定义props类型:
import { styled } from '@mui/styled-engine-sc'; // TypeScript场景:定义组件Props类型(可选但推荐) interface ChildProps { isDark?: boolean; } const Child = styled.div<ChildProps>` color: ${({ theme, isDark }) => isDark ? theme.palette.common.black : theme.palette.primary.main }; font-size: ${({ theme }) => theme.typography.body1.fontSize}; `; // Parent组件仍可使用组件选择器,同时也能访问主题 const Parent = styled.div` padding: ${({ theme }) => theme.spacing(2)}; ${Child} { color: ${({ theme }) => theme.palette.success.main}; font-weight: bold; } `;
2. 函数式语法(同样支持组件选择器)
若偏好对象式写法,styled可接受返回样式对象的函数,同样能获取theme和props:
const Child = styled('div')<ChildProps>(({ theme, isDark }) => ({ color: isDark ? theme.palette.common.black : theme.palette.primary.main, fontSize: theme.typography.body1.fontSize, })); const Parent = styled('div')(({ theme }) => ({ padding: theme.spacing(2), // 组件选择器依然生效 [Child]: { color: theme.palette.success.main, fontWeight: 'bold', }, }));
TypeScript 类型提示修复
你之前的写法未正确定义props类型,导致TypeScript无法识别变量:
- 必须通过
<PropsType>泛型参数给styled指定props类型 - MUI主题默认类型为
Theme,若自定义主题,需导入自定义主题类型替换默认类型
示例(自定义主题场景):
import { Theme } from './your-custom-theme-file'; const Child = styled.div<ChildProps>(({ theme, isDark }) => ({ // theme会自动提示自定义主题的属性 color: isDark ? theme.customColors.dark : theme.customColors.primary, }));
关键注意点
- @mui/styled-engine-sc基于styled-components,所有styled-components的写法(包括组件选择器、主题注入)均适用
- 组件选择器与主题/props访问完全兼容,无需二选一
- 模板字符串中嵌入的函数参数是包含
theme和自定义props的对象,需通过解构获取对应变量
内容的提问来源于stack exchange,提问作者Ali Kleit
相关产品推荐
相关产品推荐

