【问题标题】:Spread theme in sx prop MUI 5在 sx prop MUI 5 中传播主题
【发布时间】:2021-11-04 16:24:42
【问题描述】:

之前使用v4的代码是

const useStyles = makeStyles(theme => ({
  toolbarMargin: {
    ...theme.mixins.toolbar
  }
}))

如何使用 sx 属性将此代码迁移到 MUI v5,我尝试过这样使用它

<Box
  sx={{
    ...(theme) => theme.mixins.toolbar,
  }}
/>

但是theme 没有定义。

【问题讨论】:

    标签: javascript reactjs material-ui


    【解决方案1】:

    您可以执行以下操作:

    <Box sx={theme => theme.mixins.toolbar} />
    

    <Box sx={theme => ({
      ...theme.mixins.toolbar,
      // other sx stuff
    })} />
    

    您也可以将带有theme 作为参数的函数传递给sx 属性,它必须返回有效的sx 对象。

    【讨论】:

    • 在IDE中没有产生任何错误,但是CSS中没有工具栏样式,可能说明代码没有传到sx
    • 您确定theme.mixins.toolbar 已设置吗?请提供一个代码框让我重现该问题
    • 我刚刚测试了这两种解决方案,它适用于两种代码(使用默认 MUI 主题)
    • 您可以调试传递给sx 属性的theme,方法是将其设置为:sx={theme =&gt; {console.log(theme); return {};}}
    • 如果我像sx minHeight: (theme) =&gt; theme.mixins.toolbar.minHeight 那样定义每个样式,我就能得到结果,如果我使用你的解决方案,我就得到了名为css-0的css类
    【解决方案2】:

    对我来说,上述大多数解决方案都导致了非致命错误,因为 sx 接受对象,而不是函数。这有效:

    <Box
    sx={{
        "&": (theme) => theme["whateverYouWishToSpread"]
    }}
    >{someStuff}</Box>
    

    【讨论】:

      【解决方案3】:

      使用styled() 可能不那么复杂。

      const Container = styled('div')(theme => theme.mixins.toolbar)
      

      【讨论】:

        猜你喜欢
        • 2022-10-15
        • 1970-01-01
        • 2022-07-24
        • 1970-01-01
        • 1970-01-01
        • 2022-08-09
        • 2021-11-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多