【问题标题】:What is the type of theme in Material-UI version 5?Material-UI 版本 5 中的主题类型是什么?
【发布时间】:2021-10-12 11:43:57
【问题描述】:

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

import { Theme } from "@mui/material"

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

【问题讨论】:

    标签: reactjs typescript material-ui


    【解决方案1】:

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

    import { Theme } from '@mui/material/styles';
    
    declare module '@mui/styles' {
      interface DefaultTheme extends Theme {}
    }
    

    但请注意,不建议使用旧版包@mui/styles。查看我的另一个 answer 的更多详细信息。


    如果您已经从@mui/material/styles 导入styled:由于您使用的是打字稿,请删除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],
    }))
    

    【讨论】:

      猜你喜欢
      • 2021-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      • 2017-02-05
      • 1970-01-01
      • 2020-05-07
      • 2019-02-11
      相关资源
      最近更新 更多