【问题标题】:Using Javascript Variables with styled-components使用带有样式组件的 Javascript 变量
【发布时间】:2017-09-16 02:25:54
【问题描述】:

我正在使用styled-components 来构建我的组件。所有接受自定义值的样式属性都在我的组件中重用(应该如此)。考虑到这一点,我想使用某种全局变量,以便更新将传播到所有组件,而无需单独更新每个样式。

类似这样的:

// Variables.js

var fontSizeMedium = 16px;

// Section.js

const Section = styled.section`
  font-size: ${fontSizeMedium};
`;

// Button.js

const Button = styled.button`
  font-size: ${fontSizeMedium};
`;

// Label.js

const Label = styled.span`
  font-size: ${fontSizeMedium};
`;

我猜我的语法有误?此外,我知道在 Javascript 领域不建议使用全局变量,但在设计领域中,跨组件重用样式是绝对必须的。这里有什么取舍?

【问题讨论】:

    标签: javascript styled-components


    【解决方案1】:

    我最终想通了,所以你可以这样做,至少在使用 React 时是这样。

    您需要在一个文件中定义变量并导出它们。

    // Variables.js
    
    export const FONTSIZE_5 = '20px';
    

    然后你需要将这些变量导入到每个组件文件中。

    // Button.js
    
    import * as palette from './Variables.js';
    

    然后您可以像这样使用样式组件中的变量:

    const Button = styled.button`
      font-size: ${palette.FONTSIZE_5};
    `;
    

    【讨论】:

    • 这不只是为了静态主题吗?使用此解决方案,您无法真正呈现对变量的更改。我会选择@Ricardinho 的答案,因为这允许您动态更新主题;通过一个实际的对象。
    • 我同意在大多数情况下使用<ThemeProvider> 是最好的方法。在某些情况下(例如定义响应断点),静态变量似乎会有所帮助。但在大多数情况下,使用<ThemeProvider> 可以获得更多功能(例如,明暗模式切换、使用嵌套的ThemeProvider 自定义更深层次的元素等)
    【解决方案2】:

    <ThemeProvider> 包裹在您的应用程序周围可能会有所帮助:

    https://www.styled-components.com/docs/advanced#theming

    const theme = {
      fontColour: 'purple'
    }
    
    render() {
      return (
        <ThemeProvider theme={theme}>
          <MyApplication />
        </ThemeProvider>
      )
    }
    

    这将使所有子样式组件都可以访问主题,如下所示:

    const MyApplication = styled.section`
      color: ${props => props.theme.fontColour}
    `
    

    或者

    const MyFancyButton = styled.button`
      background: ${props => props.theme.fontColour}
    `
    

    或通过https://www.styled-components.com/docs/advanced#getting-the-theme-without-styled-components访问主题

    【讨论】:

    • 这应该是一个可以接受的答案。如果您想在样式化组件中使用类似 scss 的变量,那么您应该使用 theme 对象来保存您的所有全局设置并将其传递给 &lt;ThemeProvider&gt; 包装器。
    【解决方案3】:

    您的最终解决方案有两个原因:

    1. 仅在文件中声明一个变量并不会将其附加到整个应用的全局范围,因此除非导入其他文件,否则其他文件不知道它。
    2. 16px 不是有效值。它需要用引号括起来以使其成为字符串(就像您对'20px' 所做的那样),或者需要删除px

    我遇到了类似的情况,除了我需要我的变量是数字而不是字符串,这也有效:

    const CELL_SIZE = 12;
    const ROWS = 7;
    const CELL_GAP = 3;
    
    const BannerGrid = styled.div`
      display: grid;
      grid-template-columns: repeat(auto-fit, ${CELL_SIZE}px);
      grid-template-rows: repeat(${ROWS}, ${CELL_SIZE}px);
      grid-column-gap: ${CELL_GAP}px;
      grid-row-gap: ${CELL_GAP}px;
      grid-auto-flow: column;
    `;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-26
      • 1970-01-01
      • 2017-07-28
      • 2018-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-14
      相关资源
      最近更新 更多