我一直在创建一组可重用的组件,我一直在使用 classes prop 来设置样式以覆盖 MUI 类名。然后我将很多常见的样式提取到一个主题中,以避免在更复杂的组件中重复。主题使用 withTheme
HOC 包装每个组件。
我现在意识到,有些地方我们需要为一次性情况覆盖样式。我认为我应该能够使用 withStyles
HOC 来做到这一点,但它似乎对我不起作用。
代码笔在 https://codesandbox.io/s/overriding-a-withtheme-with-withstyle-hoc-0m9cm
MyReusableThemedComponent - 是可重用组件(实际上只是用主题包装 Material UI 选项卡)
CustomOverideTabs - 是我对 MyReusableThemedComponent 的实现,我试图通过将文本设为小写来覆盖 Material-UI textTransform。
const StyledTabs = withStyles({ root: { textTransform: "lowercase" } })(
MyReusableThemedComponent
);
我相信 transform: uppercase 是 MuiTab-root 类的默认设置,但即使在主题中指定它似乎也没有什么不同。
TIA
最佳答案
withStyles
的效果是将 classes
Prop 注入(inject)包装组件(在您的情况下为 MyReusableThemedComponent
),但您不是除了在创建 tabsStyle
期间将整个 props
对象传递给 useStyles
之外,对注入(inject)的 prop 做任何事情。这将合并两组类,但随后您需要在某处利用 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
,或者如果您保持 Tab
呈现不变,则 textTransform
将按预期工作,您可以获得它通过将 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
的主题中指定样式覆盖,但主题的结构不正确。主题中的 MuiFab
和 MuiTab
条目应该在 overrides
键中。这是您的沙箱的修改版本,演示了这一点:https://codesandbox.io/s/overriding-a-withtheme-with-withstyle-hoc-ju296
相关文档:
关于css - 在已经使用 withTheme() 的情况下使用 withStyles() 覆盖 material-ui 主题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59310583/