模板文字无法与 Tailwind CSS 一起正常工作

use*_*491 6 css user-interface reactjs template-literals tailwind-css

我将十六进制颜色传递到道具中,并尝试用它设置元素的背景。这是我的代码:

 let cardColourRGB: string;
 if (cardColour) {
   cardColourRGB = "[" + cardColour + "]";
   console.log(cardColourRGB);
 } else {
   cardColourRGB = "white/50"
 }
Run Code Online (Sandbox Code Playgroud)

在函数中return

 <div className={`bg-${cardColourRGB}`}></div>
Run Code Online (Sandbox Code Playgroud)

传递某些颜色可以,但其他颜色则不行。例如,传入 #AAA32E 作为 prop 不会设置颜色,但直接设置颜色就可以了:

<div className={`bg-[#AAA32E]`}></div>
Run Code Online (Sandbox Code Playgroud)

为什么会这样呢?

kri*_*yaa 12

根据官方文档,tailwind.css不希望有这样的classNames

\n

正如文件所说:

\n
    \n
  • Tailwind 如何提取类名的最重要含义是,它只会查找源文件中作为完整不间断字符串存在的类。

    \n
  • \n
  • 如果您使用字符串插值或将部分类名连接在一起,Tailwind 将找不到它们,因此不会生成相应的 CSS:

    \n
  • \n
\n

不要动态构造类名

\n
<div class="text-{{ error ? 'red' : 'green' }}-600"></div>\n
Run Code Online (Sandbox Code Playgroud)\n

相反,请确保您使用的任何类名\xe2\x80\x99 都完整存在

\n
<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>\n
Run Code Online (Sandbox Code Playgroud)\n

因此,对于您的情况,请使用以下代码:

\n
<div class="{{ cardColour ? 'bg-[#AAA32E]' : 'bg-white-50' }}"></div>\n
Run Code Online (Sandbox Code Playgroud)\n

希望能帮助到你!

\n