我正在寻找有关 @material-ui/core
的建议,
我希望有一种一致的方法来处理 CSS-in-js 生成的具有不确定数字后缀的类名,同时仍然使用 @material-ui/core
的 styled()
函数(如果可能的话)。
“@material-ui/core/styles
生成的类名是不确定的”(https://material-ui.com/styles/advanced/#class-names),但到目前为止,我公司的项目都使用styled()
函数,用于包装组件以应用样式。
它工作得很好,直到我想覆盖其中一个伪类如何应用于我正在设置样式的根元素。在这一点上,如果我尝试使用常规的旧类选择器来控制特定状态下的样式,如果类上没有后缀,它就会起作用,但是只要 JSS 生成的类名有一个数字后缀, 它坏了。
When I say "suffix" I'm referring to how a component's root className might be
.makeStyles-root
but when the className is generated for that specific instance, it likely has a numeric suffix appended:.makeStyles-root-123
组件:InputLabel
https://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];
我也试过传递类
(但那似乎根本不起作用)
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
最佳答案
据我所知,使用 styled()
是不可能的,
所以我只是按照其他帖子的建议使用了 makeStyles()
。
但是我混合使用了两者,这样我仍然可以将我的样式保存在一个单独的文件中。
const useLabelStyles = makeStyles((theme) => ({
root: {
color: theme.text.primary,
},
formControl: {
transform: 'translate(2px, 8px) scale(1)',
},
shrink: {
transform: 'translate(0) scale(0.6)',
},
}));
export const InputLabel = styled((props) => {
const theme = useTheme();
const classes = useLabelStyles(theme);
return (
<MuiInputLabel
classes={classes}
{...props}
/>
);
})({});
https://stackoverflow.com/questions/64472230/