【问题标题】:Overriding a material-ui theme using withStyles() while already using withTheme()在已经使用 withTheme() 的同时使用 withStyles() 覆盖 Material-ui 主题
【发布时间】:2020-04-06 04:46:21
【问题描述】:

我一直在创建一组可重用组件,我使用 classes 属性对其进行样式化以覆盖 MUI 类名。然后我将许多常见的样式提取到一个主题中,以避免在更复杂的组件中重复。主题是使用withTheme HOC 包装每个组件。

我现在意识到有些地方我们需要为一次性案例覆盖样式。我认为我应该能够使用 withStyles HOC 来做到这一点,但它似乎对我不起作用。

https://codesandbox.io/s/overriding-a-withtheme-with-withstyle-hoc-0m9cmCodepen

MyReusableThemedComponent - 是可重用组件(实际上只是用主题包装 Material UI 选项卡)

CustomOverideTabs - 是我的 MyReusableThemedComponent 的实现,我试图通过使文本小写来覆盖 Material-UI textTransform。

const StyledTabs = withStyles({ root: { textTransform: "lowercase" } })(
  MyReusableThemedComponent
);

我相信 transform: uppercase 是 MuiTab-root 类的默认设置,但即使在主题中指定它似乎也没有什么区别。

TIA

【问题讨论】:

    标签: css reactjs tabs themes material-ui


    【解决方案1】:

    withStyles 的效果是将classes 道具注入到包装的组件中(在您的情况下为MyReusableThemedComponent),但除了将整个props 对象传递给useStyles 在创建tabsStyle 期间。这将合并两组类,但是您需要在某处利用 tabsStyle.root 才能产生任何效果。

    您有以下代码用于呈现Tab 元素:

                <Tab
                  key={index}
                  label={tab.tabTitle ? tab.tabTitle.toString() : "tab" + { index }}
                  disabled={tab.disabled}
                  classes={{
                    root: tabsStyle.tabRoot,
                    selected: tabsStyle.selectedTab
                  }}
                />
    

    这是利用tabsStyle.tabRoot 作为root 类,但tabRoot 尚未在任何地方定义。如果您将其更改为root: tabsStyle.root,则textTransform 将按预期工作,或者如果您保持Tab 呈现不变,您可以通过将withStyles 调用中的规则名称更改为tabRoot 来使其工作(例如withStyles({ tabRoot: { textTransform: "lowercase" } }))。

    使用tabsStyle.tabRoot 的示例(即仅更改withStyles 参数):https://codesandbox.io/s/overriding-a-withtheme-with-withstyle-hoc-fxybe

    使用tabsStyle.root 的示例(即仅在渲染Tab 元素时更改classes 属性的指定方式):https://codesandbox.io/s/overriding-a-withtheme-with-withstyle-hoc-ptj87


    沙盒中的一个单独问题是,您似乎试图在 ConditionalThemeWrapper 的主题中指定样式覆盖,但主题的结构不正确。主题中的MuiFabMuiTab 条目应位于overrides 键内。这是您的沙盒的修改版本,展示了这一点:https://codesandbox.io/s/overriding-a-withtheme-with-withstyle-hoc-ju296

    相关文档:

    【讨论】:

    • 感谢您花时间提供如此完整的答案和清晰的解释。 (关于缺少 'overrides' 关键字的评论是我在删除沙盒主题时的错误 - 我不小心删除了它。很好发现。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 2019-10-06
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    相关资源
    最近更新 更多