【发布时间】:2023-03-27 19:36:01
【问题描述】:
我正在寻找关于 @material-ui/core 的建议,
TLDR;
如果可能,我希望采用一致的方法来处理 CSS-in-js 生成的具有不确定数字后缀的类名,同时仍使用 @material-ui/core 的 styled() 函数。
具体
“@material-ui/core/styles 生成的类名是不确定的”(https://material-ui.com/styles/advanced/#class-names),但到目前为止,在我的公司,我从事的项目都使用了 styled() 函数来包装组件以应用样式。
它工作得很好,直到我想覆盖其中一个伪类如何应用于我正在设置样式的根元素。此时,如果我尝试使用常规的旧类选择器来控制特定状态下的样式,如果类上没有后缀,它将起作用,但只要 JSS 生成的 className 具有数字后缀,它坏了。
当我说“后缀”时,我指的是组件的根 className 可能是
.makeStyles-root,但是当为该特定实例生成 className 时,它可能附加了一个数字后缀:.makeStyles-root-123
例如:
组件:InputLabelhttps://material-ui.com/api/input-label/#inputlabel-api
我想摆弄发生的转换,它来自.MuiInputLabel-formControl,但随后该转换被.MuiInputLabel-shrink 覆盖。
如果我尝试使用常规的类选择器:
export const InputLabel = styled(MuiInputLabel)({
`&.MuiInputLabel-formControl`: {
transform: 'translate(2px, 8px) scale(1)',
},
`&.MuiInputLabel-shrink`: {
transform: 'translate(0) scale(0.6)',
},
});
只有在 JSS 类没有后缀时才有效,
如果我尝试使用规则名称(我认为 styled() 实际上不支持它)
export const InputLabel = styled(MuiInputLabel)({
formControl: {
transform: 'translate(2px, 8px) scale(1)',
},
shrink: {
transform: 'translate(0) scale(0.6)',
},
});
它只是对元素应用无效规则:
formControl: [object Object]
shrink: [object Object];
我也尝试过传递classes(但这似乎根本不起作用)
export const InputLabel = styled((props) => (
<MuiInputLabel
classes={{
formControl: {
transform: 'translate(2px, 8px) scale(1)',
},
shrink: {
transform: 'translate(0) scale(0.6)',
},
}}
{...props}
/>
))({});
补充说明
-
我不想使用主题覆盖(我想这会在此处启用这些规则),因为我不希望这种样式应用于 InputLabel 的所有实例
-
这让我倾向于使用 hook api / makeStyles() :https://material-ui.com/styles/basics/#hook-api
- 但这并不适合当前带有样式文件的模式。
相关
- 我见过这些类似的问题:
- jss to override a material-ui nondeterministic class
- How override material ui style with hooks
- 不同之处在于,如果可能,我会尽量避免使用 hook api。
【问题讨论】: