如何在React JS中使用LESS变量

时间:2018-08-21 10:24:41

标签: javascript css reactjs

我有以下带有硬编码颜色的标签:

<p style={{ color: '#646464' }}>

我想使用我定义的CSS变量,我们将其称为@tertiary-col,我将如何使用该变量? <p style={{ color: '@tertiary-col' }}>似乎无效

3 个答案:

答案 0 :(得分:3)

您不能在JSX中使用来自CSS预编译器的变量,例如LESS。您可以使用JavaScript变量,例如

const redColor = "#FF0000";

<p style={{ color: redColor }}

或者给它一个className,然后让您的CSS处理其余部分。

另一种选择是添加诸如less-vars-to-js之类的加载程序,以将您的LESS变量(假设您使用@时的意思是LESS)映射到JavaScript。

另一种选择是使用native CSS variables作为其他建议的答案,您可以在JavaScript中使用这些变量,其不利之处在于它们aren't supported by all browsers(尚未)。

答案 1 :(得分:2)

可以使用本机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/

答案 2 :(得分:1)

在React中使用本机css变量:

假设您要在特定元素中的任何文本节点的明暗主题之间切换:

const LightDarkSpan = ({ children }) => (
  <span style={{
    color: 'var(--text-color, black)'
  }}>
    {children}
  </span>
);

然后,任何父项都可以设置该变量,并且它实际上充当任何明确选择使用该特定CSS变量的子元素的上下文:

// rendered
<div style={{
  backgroundColor: 'black',
  '--text-color': 'white'
}}>
  <article>
    <LightDarkSpan>testing</LightDarkSpan>
  </article>
</div>

Reference