将Javascript变量与样式组件一起使用 [英] Using Javascript Variables with styled-components

查看:82
本文介绍了将Javascript变量与样式组件一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using styled-components to build my components. All style properties which accept custom values are reused throughout my components (as it should be). With that in mind, I'd like to use some sort of global variables so that updates will propagate to all components without needing to update each style individually.

像这样的东西:

// 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领域不推荐全局变量,但在设计中,组件之间的重用样式是绝对必要的。这里的权衡是什么?

I guess I'm getting the syntax wrong though? Also, I know global variables are not recommended in Javascript land, but in design land reusing styles across components is an absolute must. What are the trade-offs here?

推荐答案

我最终想出来了,所以这里有你怎么做,至少如果使用React。

I eventually figured this out, so here's how you can do it, at least if using React.

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

You need to define the variables in one file and export them.

// Variables.js

export const FONTSIZE_5 = '20px';

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

Then you need to import those variables into each component file.

// Button.js

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

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

Then you can use the variables in your styled-components like this:

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

这篇关于将Javascript变量与样式组件一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆