具有相同值的 JSS 选择器数组

JSS array of selectors with same value

我为使用 JSS 的 React 项目创建了一个全局样式表。我对 CSS、SASS 和 CSS 模块非常满意,但这是我第一次使用 JSS。

所有标题都具有相同的边距。出于可维护性和性能方面的原因,我不想将它键入多种类型或让它多次出现在编译样式中。我也不想在所有标题中都添加 class。

我的 JSS 由于选择器数组 ([h1, h3, h4, h5, h6]) 而无法工作:

const globalStyles = theme => ({
    '@global': {
        body: {
            fontFamily: ['Roboto', 'sans-serif'].join(','),
        },
        [h1, h3, h4, h5, h6]: {
            margin: '0 0 .35em 0'
        },
        h1: {
            fontSize: theme.typography.pxToRem(40),
            fontWeight: 600
        },
        h3: {
            fontSize: theme.typography.pxToRem(34),
            lineHeight: 1.75
        },
        h5: {
            fontSize: theme.typography.pxToRem(28),
            lineHeight: 'normal'
        },
        h6: {
            fontSize: theme.typography.pxToRem(20),
            lineHeight: 'normal'
        }
    }
})

export default globalStyles

我正在尝试实现以下输出:

body {
    font-family: Roboto, sans-serif
}
h1, h3, h4, h5, h6 {
    margin: 0 0 .35em 0
}
h1 {
    font-size: 2.5rem;
    font-weight: 600;
}
h3 {
    font-size: 2.125rem;
    line-height: 1.75;
}
h5 {
    font-size: 1.75rem;
    line-height: normal;
}
h6 {
    font-size: 1.25rem;
    line-height: normal;
}

这可以用 JSS 实现吗?我已经阅读了一些关于 JSS 的资料,但我还没有找到解决方案。

只需将它们放入以逗号分隔的字符串中,有点像您在 常规老式 CSS:

中的做法
'@global': {
  'h1, h3, h4, h5, h6': {
     margin: "0 0 .35em 0"
  }
}

可以使用例如。 […].join(', ') 来构造字符串,当然(就像上面 font-family 所做的那样)。

[h1, h3, h4, h5, h6] 是错误的 javascript 语法,不是特定于 JSS。 属性 中只允许有一个变量。所以你可以写 [h] 其中 h 是一个变量,你必须提前定义或直接作为字符串文字 ['h1'],这没有多大意义,因为你可以直接将它用作 属性。如果你愿意,如果你真的需要这些变量,你也可以这样表达。它之所以有效,是因为内部数组将被转换为字符串,默认情况下,它会在 js 中转换为逗号分隔值:[1,2].toString()

  const h1 = 'h1'
  const h2 = 'h2'

  '@global': {
    [[h1, h2]]: {
      color: 'red'    
    }
  }