在 createMuiTheme 的覆盖中使用 theme.spacing 函数

Use theme.spacing function in override in createMuiTheme

提问人:Jordan 提问时间:5/20/2020 更新时间:11/20/2023 访问量:1076

问:

在设置主题时,是否有首选方法来使用主题间距?我一直在对这些值进行硬编码,并且在大多数情况下没有问题,因为我的大多数项目都没有覆盖默认主题间距,但是能够在我的覆盖中使用主题间距会很好吗?createMuiTheme

ReactJS Material-UI 主题

评论

1赞 ihist 1/13/2021
这不是您需要的答案,但它可能会帮助您 stackoverflow.com/questions/47977618/......
0赞 Jordan 1/14/2021
@ihist如果我没记错的话,这基本上就是我最终做的事情
0赞 Akis 7/2/2022
@Jordan,如果我理解了您想要实现的正确目标,MUI 文档应该可以帮助您: mui.com/material-ui/customization/spacing .const theme = createTheme({ spacing: [0, 4, 8, 16, 32, 64], });主题间距(2);= '8px'

答:

6赞 Jordan 7/5/2022 #1

在新的 Mui v5 中,通过使用传递给样式名称的函数解决了这个问题

export default createTheme({
  components: {
    MuiAppBar: {
      styleOverrides: {
        root: ({ theme }) => ({
          margin: theme.spacing(2)
        })
      }
    }
  }
})
0赞 Michael Lynch 11/20/2023 #2

TypeScript(打字稿)

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

interface StyleOverridesParams {
  theme: Theme
}

export default createTheme({
  components: {
    MuiAppBar: {
      styleOverrides: {
        root: ({ theme }: StyleOverridesParams) => ({
          margin: theme.spacing(2)
        })
      }
    }
  }
})

ownerState,“运行时道具和内部状态的组合”,在回调中也可用。

https://mui.com/blog/callback-support-in-style-overrides/