代码之家  ›  专栏  ›  技术社区  ›  vsync

样式化组件局部变量

  •  0
  • vsync  · 技术社区  · 7 年前

    来自 SCSS ( 萨斯 )

    什么是合适的 样式化组件 实施以下内容 SCSS 代码?

    SCSS:

    .circle{
      $size: 16px;  // <-- SCSS FTW. use such a trick in styled-components
    
      height: $size;
      width: $size;
      .. rest of properties...
    }
    

    目前 样式化组件 ( Circle )看起来像这样:

    ...lots of other styled exports
    
    export const Circle = styled.div`
      height: 16px;
      width: 16px;
      background: red;
      border-radius: 50%;
    `
    
    ...lots of other styled exports
    

    问题是,我想让这个“毫无意义” size 变量在使用它的同一上下文中(就像 SCSS )因为没有其他人关心或永远不会关心它。我不认为把一个变量放在某个地方然后用它 '${size}' 是一种“干净”的方式。这样的策略很小,而且会导致混乱的代码库。

    1 回复  |  直到 7 年前
        1
  •  0
  •   shahrooz    7 年前

    解决此问题的一种方法是创建一个单独的文件,其中包含稍后要在样式文件中使用的所有变量:

    export const Variables = {
      size: '16px',
      bgColor: 'red',
    }
    

    然后您可以导入它:

    import { Variables } from './Variables'
    
    export const Circle = styled.div`
      height: ${Variables.size};
      width: ${Variables.size};
      background: ${Variables.bgColor};
      border-radius: 50%;
    `
    
    
        2
  •  -1
  •   vsync    7 年前

    我设计了一个巧妙的技巧,只为特定范围封装变量:

    styled.h1(({size='4em', color='lime'}) => `
      font-size: ${size};
      color: ${color};
      text-align: center;
    `)
    

    我写了一个 Medium post 在过去,它打破了这种方法的解释