首页 > 解决方案 > Material-UI 版本 5 中的主题类型是什么?

问题描述

我正在将我的项目更新到MUI 版本 5。推荐使用情感 CSS。我想使用该theme物业。现在打字稿要求输入theme. 下面的版本不起作用。如何提供类型?

import { Theme } from "@mui/material"

const Root = styled('div')(({ theme: Theme }) => ({
  background: theme.palette.grey[50],
}))

标签: reactjstypescriptmaterial-ui

解决方案


如果您碰巧从 导入styledAPI @mui/styles,那么它不会工作,因为它没有提供开箱即用的 MUI 主题。您需要将createTheme其传递给ThemeProvider自己,然后增加类型,DefaultTheme因为默认情况下它是一个空接口:

import { Theme } from '@mui/material/styles';

declare module '@mui/styles' {
  interface DefaultTheme extends Theme {}
}

但请注意,不建议使用 legacy 包@mui/styles。请参阅我的其他答案的更多详细信息。


如果您已经styled从以下位置导入@mui/material/styles:由于您使用的是打字稿,请删除Theme类型,该styled函数可以theme在回调中推断属性的类型,因此您无需执行任何操作:

const Root = styled('div')(({ theme }) => ({
  background: theme.palette.grey[50],
}))

但理论上,如果theme没有类型,这就是你添加它的方式:

const Root = styled('div')(({ theme }: { theme: Theme }) => ({
  background: theme.palette.grey[50],
}))

推荐阅读