【问题标题】:JSS array of selectors with same value具有相同值的选择器的 JSS 数组
【发布时间】:2019-06-06 22:43:02
【问题描述】:

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

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

由于选择器数组([h1,h3,h4,h5,h6]),我的 JSS 不起作用:

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 上做了一些阅读,但我没有找到解决方案。

【问题讨论】:

    标签: javascript reactjs jss


    【解决方案1】:

    [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'    
        }
      }
    

    【讨论】:

      【解决方案2】:

      只需将它们放入逗号分隔的字符串中,就像您在常规的老式 CSS 中所做的那样:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-15
        • 2012-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-06
        • 2021-12-03
        • 2021-03-22
        相关资源
        最近更新 更多