简体   繁体   English

如何在 React JS 中使用 LESS 变量

[英]How to use LESS variable in React JS

I have the following tag with a hard-coded color:我有以下带有硬编码颜色的标签:

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

I want to use a LESS variable that I've defined instead, let's called it @tertiary-col , how would I use this variable?我想使用我定义的 LESS 变量,我们称之为@tertiary-col ,我将如何使用这个变量? <p style={{ color: '@tertiary-col' }}> doesn't seem to work <p style={{ color: '@tertiary-col' }}>似乎不起作用

You cannot use variables from CSS-precompilers like LESS inside of your JSX.您不能在 JSX 中使用来自 CSS 预编译器(如 LESS)的变量。 You can either use JavaScript variables like您可以使用 JavaScript 变量,例如

const redColor = "#FF0000";

<p style={{ color: redColor }}

Or give it a className and let your CSS handle the rest.或者给它一个className ,让你的 CSS 处理剩下的事情。

Another option would be to add a loader like less-vars-to-js to map your LESS variables (I'm assuming you mean LESS as you're using @ ) to JavaScript.另一种选择是添加一个像less-vars-to-js这样的加载器来将你的 LESS 变量(我假设你的意思是 LESS,因为你使用@ )到 JavaScript。

And another option would be to use native CSS variables as other answers suggested, you can use these variables within your JavaScript, the downside on this is that they aren't supported by all browsers (yet).另一种选择是使用本机 CSS 变量作为其他答案的建议,您可以在 JavaScript 中使用这些变量,这样做的缺点是并非所有浏览器都支持它们(尚)。

It is possible to use native var() to do this.可以使用原生var()来做到这一点。

By placing the variable in :root then it becomes available anywhere you need to use it.通过将变量放在:root它就可以在您需要使用它的任何地方使用。

You would do --tertiary-col: @tertiary-col;你会做--tertiary-col: @tertiary-col; , but for the purposes of the snippet I have put in an actual hex value. ,但为了片段的目的,我已经输入了一个实际的十六进制值。

 :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>

Here is an excellent tutorial on css variables: https://codepen.io/abcretrograde/full/xaKVNx/这是一个关于 css 变量的优秀教程: https : //codepen.io/abcretrograde/full/xaKVNx/

For using native css variables in React:在 React 中使用原生 css 变量:

Let's say you want to toggle between light and dark themes for any text nodes in a certain element:假设您想在某个元素中的任何文本节点的浅色和深色主题之间切换:

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

Then, any parent can set that variable, and it effectively acts as context to any child element that explicitly chooses to use that specific CSS variable:然后,任何父元素都可以设置该变量,它有效地充当任何明确选择使用该特定 CSS 变量的子元素的上下文:

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

Reference 参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM