将 Javascript 变量与样式组件一起使用

Using Javascript Variables with styled-components

我正在使用 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 领域不推荐使用全局变量,但在设计领域,跨组件重用样式是绝对必须的。这里的取舍是什么?

我最终弄明白了,所以这里是你如何做到的,至少如果使用 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};
`;

<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

访问主题

您的最终解决方案之所以有效,有两个原因:

  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;
`;