29

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

4

3 回答 3

43

我最终弄清楚了这一点,所以这是你可以做到的,至少在使用 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};
`;
于 2017-04-19T21:47:48.830 回答
40

将 a 包裹<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访问主题

于 2017-08-15T01:17:16.513 回答
2

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

  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;
`;
于 2020-06-12T05:07:01.967 回答