【问题标题】:Using :not pseudo-class across components跨组件使用 :not 伪类
【发布时间】:2018-02-07 07:21:55
【问题描述】:

我有一个<Section> 组件:

const styles = theme => ({
  section: {
    backgroundColor: theme.colors.primary,
    color: theme.colors.white,

    '& a:not(.button)': {
      color: 'currentColor',
      textDecoration: 'underline',
    },
  },
});

还有一个<Button> 组件:

const styles = theme => ({
  button: {
    backgroundColor: theme.colors.light,
    color: theme.colors.dark,
    padding: theme.spacing.default,
  },
});

基本上,我想在<Section> 中使用<Button>,而不是覆盖它的颜色。

我不能使用& a:not($button),因为它在不同的组件中。

【问题讨论】:

  • this expects .button to be global, while it is not 是什么意思?
  • 生成的类类似于.is-primary-0-24 a:not(.button),但我的按钮组件生成.button-0-24
  • 那你用什么来操作 css 类名呢?

标签: reactjs jss


【解决方案1】:

不要使用选择器隐式覆盖组件样式。这是一种非常脆弱的方法,因为它会破坏封装,并且在某些时候会破坏您的样式。

您应该在按钮组件中使用color: inherit 并让父级始终定义颜色或使用显式覆盖:

  1. 在子节点中接受类名,在父节点中使用您的颜色定义 css 规则。 (静态时很好)
  2. 使用主题(静态和预定义时很好)
  3. 使用函数值和道具http://cssinjs.org/json-api#function-values(如果高度动态则很好)

【讨论】:

  • 所以如果我有a: { color: 'red' }select: { backgroundColor: 'red' } 那么如何让我的锚可见?特别是如果用户在 Markdown 编辑器中创建链接,我无法创建一个无论如何都令人讨厌的 <Link> 组件。
  • 现在我想我的解决方案是使用:not 来不隐式覆盖组件的样式?
  • 如果你的锚点周围没有组件,所以基本上它们是 Markdown 组件的一部分,然后用 '& a' 定位它们。
【解决方案2】:

更好的解决方案是将选择器修改为:a:not([class^="button"]),它将针对 JSS 生成的类。

【讨论】:

    【解决方案3】:

    我刚刚测试的一个可能的解决方案是简单地将!important 添加到<Button> 样式中。感觉很脏……

    【讨论】:

      猜你喜欢
      • 2011-03-05
      • 2017-12-14
      • 2022-01-15
      • 1970-01-01
      • 2020-01-19
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 2015-11-03
      相关资源
      最近更新 更多