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

col*_*ite 18 javascript 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};
`;
Run Code Online (Sandbox Code Playgroud)

我想我的语法错了但是?此外,我知道Javascript领域不推荐全局变量,但在设计中,组件之间的重用样式是绝对必要的.这里的权衡是什么?

col*_*ite 24

我最终想到了这一点,所以这就是你如何做到这一点,至少如果使用React.

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

// Variables.js

export const FONTSIZE_5 = '20px';
Run Code Online (Sandbox Code Playgroud)

然后,您需要将这些变量导入每个组件文件.

// Button.js

import * as palette from './Variables.js';
Run Code Online (Sandbox Code Playgroud)

然后你可以使用样式组件中的变量,如下所示:

const Button = styled.button`
  font-size: ${palette.FONTSIZE_5};
`;
Run Code Online (Sandbox Code Playgroud)

  • 这不是仅用于静态主题吗?使用此解决方案,您无法真正呈现对变量的更改。我会使用@Ricardinho的答案,因为这可以让您动态更新主题。通过一个实际的对象。 (2认同)

Ric*_*nho 24

包装<ThemeProvider>您的应用程序可能会有所帮助:

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

const theme = {
  fontColour: 'purple'
}

render() {
  return (
    <ThemeProvider theme={theme}>
      <MyApplication />
    </ThemeProvider>
  )
}
Run Code Online (Sandbox Code Playgroud)

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

const MyApplication = styled.section`
  color: ${props => props.theme.fontColour}
`
Run Code Online (Sandbox Code Playgroud)

要么

const MyFancyButton = styled.button`
  background: ${props => props.theme.fontColour}
`
Run Code Online (Sandbox Code Playgroud)

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

  • 这应该是一个公认的答案.如果你想在样式组件中有一个类似scss的变量,那么你应该使用`theme`对象来保存所有的全局设置并将它传递给`<ThemeProvider>`包装器. (2认同)

Lan*_*ith 5

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

  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;
`;
Run Code Online (Sandbox Code Playgroud)