Material-UI v5中theme的类型是什么?如何在styled组件中正确声明?
你的代码问题出在混淆了TypeScript的「变量重命名」和「类型注解」语法:你写的{ theme: Theme }实际作用是将解构得到的theme变量重命名为Theme,而非给theme指定Theme类型,所以后续调用theme时会找不到对应变量,类型校验也会失败。
正确写法分两种场景:
场景1:使用MUI内置的styled
如果你用的是从@mui/material或@mui/material/styles导出的styled,默认已经内置了Theme类型推导,你只需要把重命名的语法改成类型注解即可:
import { Theme, styled } from "@mui/material" const Root = styled('div')(({ theme }: { theme: Theme }) => ({ background: theme.palette.grey[50], }))
如果没有自定义扩展Theme类型,甚至可以省略手动类型注解,MUI的styled会自动推导theme类型:
import { styled } from "@mui/material" const Root = styled('div')(({ theme }) => ({ background: theme.palette.grey[50], }))
场景2:直接使用Emotion原生的styled
如果你用的是@emotion/react导出的原生styled,可以通过全局类型声明让所有styled的theme自动继承MUI的Theme类型,不需要每次手动加注解:
- 新建类型声明文件(例如
src/emotion.d.ts),添加如下内容:
import '@emotion/react' import type { Theme as MuiTheme } from '@mui/material' declare module '@emotion/react' { export interface Theme extends MuiTheme {} }
- 之后写styled代码时就不需要额外声明theme类型了:
import { styled } from '@emotion/react' const Root = styled('div')(({ theme }) => ({ background: theme.palette.grey[50], }))
内容的提问来源于stack exchange,提问作者vuvu
相关产品推荐
相关产品推荐

