Material-UI 版本 5 中的主题类型是什么?

vuv*_*uvu 4 typescript reactjs material-ui

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

import { Theme } from "@mui/material"

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

Nea*_*arl 8

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

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

declare module '@mui/styles' {
  interface DefaultTheme extends Theme {}
}
Run Code Online (Sandbox Code Playgroud)

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


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

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

但理论上,如果theme是无类型的,则可以这样添加它:

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