我有一个带有硬编码颜色的标签:
<p style={{ color: '#646464' }}>
我希望使用我定义的LESS变量,让我们称之为
@tertiary-col
,我该如何使用这个变量呢?<p style={{ color: '@tertiary-col' }}>
似乎不能正常工作。我有一个带有硬编码颜色的标签:
<p style={{ color: '#646464' }}>
@tertiary-col
,我该如何使用这个变量呢?<p style={{ color: '@tertiary-col' }}>
似乎不能正常工作。可以使用本地 var()
来实现这一点。
将变量放置在 :root
中,然后它就可以在您需要使用它的任何地方使用。
您可以执行 --tertiary-col: @tertiary-col;
,但是为了演示目的,我已经放入了实际的十六进制值。
:root {
--tertiary-col: @tertiary-col; /* this is what you would do */
--tertiary-col: #646464; /* @tertiary-col; */
}
<p style="color: var(--tertiary-col)">Some text</p>
这是一篇关于CSS变量的优秀教程:https://codepen.io/abcretrograde/full/xaKVNx/
在JSX中,您无法使用来自CSS预处理器(如LESS)的变量。您可以使用JavaScript变量,例如
const redColor = "#FF0000";
<p style={{ color: redColor }}
或者给它一个className
,让你的CSS处理其余部分。
另一个选择是添加一个加载器,例如less-vars-to-js,以将您的LESS变量(假设您使用的是@
)映射到JavaScript中。
另一个选项是使用本地CSS变量,正如其他答案所建议的那样,您可以在JavaScript中使用这些变量,缺点是它们尚未被所有浏览器支持(但还不是所有浏览器都支持)。
color: --some-css-var
。 - Jared Smith@var
的浏览器。 - Richard Parnaby-Kingconst LightDarkSpan = ({ children }) => (
<span style={{
color: 'var(--text-color, black)'
}}>
{children}
</span>
);
// rendered
<div style={{
backgroundColor: 'black',
'--text-color': 'white'
}}>
<article>
<LightDarkSpan>testing</LightDarkSpan>
</article>
</div>
<p style={{ color: tertiary-col }}>
这段代码中,我不认为“tertiary-col”是一个有效的变量名称。 - hanish singla