【问题标题】:How can I consistently overwrite JSS styles which have indeterminate suffixes?如何始终覆盖具有不确定后缀的 JSS 样式?
【发布时间】:2023-03-27 19:36:01
【问题描述】:

我正在寻找关于 @material-ui/core 的建议,

TLDR;

如果可能,我希望采用一致的方法来处理 CSS-in-js 生成的具有不确定数字后缀的类名,同时仍使用 @material-ui/corestyled() 函数。

具体

@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

    • 但这并不适合当前带有样式文件的模式。

相关

【问题讨论】:

    标签: reactjs jss css-in-js


    【解决方案1】:

    据我所知,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}
        />
      );
    })({});
    

    【讨论】:

      猜你喜欢
      • 2019-04-17
      • 2022-09-28
      • 2019-04-23
      • 1970-01-01
      • 2018-11-05
      • 2019-06-01
      • 2019-01-02
      • 2015-05-04
      • 2015-02-02
      相关资源
      最近更新 更多