reactjs - 如何始终覆盖具有不确定后缀的 JSS 样式?

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

TLDR;

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

具体

@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

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

相关

  • 我见过这些类似的问题:
    • jss to override a material-ui nondeterministic class
    • How override material ui style with hooks
    • 不同之处在于我尽可能避免使用 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/

相关文章:

javascript - Windows Localhost 中的 Wiki.js 安装

java - 修改 tomcat 上静态 Assets 的 header cookie 并使用 ap

reactjs - Stripe 参数_invalid_integer

java - 微服务之间的通信和使用 REST 的内聚

python-3.x - 一个FITS文件的坐标转换问题

authentication - Telegram 登录小部件因禁用跨站点 cookie 而损坏

ansible - Ansible 中角色的串行执行

matlab - 由凸包创建的曲面上点值的插值

node.js - AWS sdk 使用 sso 获取凭证

firebase - 使用 Mockito 为 Firebase 用户身份验证设置单元测试