gpt4 book ai didi

javascript - 使用带有样式组件的 Javascript 变量

转载 作者:行者123 更新时间:2023-12-03 13:14:59 24 4
gpt4 key购买 nike

我正在使用 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};
`;

关于javascript - 使用带有样式组件的 Javascript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43502813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com