模板不适用于 React 中的 Tailwind



如果我把颜色直接放在像"bg-cianTheme"这样的顺风类中,它就可以工作了。但是如果我使用像"bg-${primaryColorTheme}"这样的javascript模板,上面的代码不工作。为什么会发生,如何修复?

代码:

import { BsGithub, BsLinkedin } from 'react-icons/bs'
export interface INewProfileCardProps {
photo: string
github: string
linkedin: string
colors: string[]
primaryColorTheme: string // tailwind refence collor
secondaryColorTheme: String //tailwind reference collor
terciaryColorTheme: string //tailwind reference collor
labelName: string
}
export function NewProfileCard({
photo,
github,
linkedin,
colors,
labelName,
}: INewProfileCardProps) {
const [primaryColorTheme, secondaryColorTheme, terciaryColorTheme] = colors    
console.log(`bg-${primaryColorTheme}`)
return (
<div className="flex items-center justify-center">
<div>{/* <p className="text-[250px]">{'<'}</p> */}</div>
<div className=" relative h-[202px] w-[404px] rounded-xl bg-whiteIcon px-4 py-8 pt-2">
<div
className={`bg-${primaryColorTheme} relative  flex h-full w-full`}
>
<img
className="absolute bottom-0"
src={photo}
alt="personal-photo"
></img>
</div>
<div className="absolute flex">
<div
className={`flex items-center justify-center font-bold text-${primaryColorTheme} bg-${primaryColorTheme} rounded-l-xl px-6 py-2`}
>
<BsGithub className="text-2xl" />
<p className="ml-3 text-lg">Git Hub</p>
</div>
<div
className={` bg-${secondaryColorTheme} ${primaryColorTheme} flex items-center justify-center rounded-r-xl px-6 py-2 font-bold`}
>
<BsLinkedin className="text-2xl" />
<p className="ml-3 text-lg">Linkedin</p>
</div>
</div>
</div>
<div>
{/* <p className="text-[250px]">
<span className={`text-${primaryColorTheme}`}>/</span>
{'>'}
</p> */}
</div>
</div>
)
}

我尝试用模板的顺风类中的变量来改变颜色,但是不工作。

问题是当你有这样的插值字符串时,postcss找不到那个类。你可以把它添加到tailwind.config.js

safelist: ["bg-somecolor"]

或者你可以找到不使用插值的方法

除了pguardiano的答案之外,您还可以通过直接调用style属性来实现相同的功能,因为postCSS只呈现模板中现成的内容…

在您的例子中,您可以将十六进制代码直接发送给变量并将其传递给style属性。例子:

<div
className="relative  flex h-full w-full"
style="{{ background: primaryColorThemeColor }}"
>
<img
className="absolute bottom-0"
src={photo}
alt="personal-photo"
/>
</div>

如果你想亲自动手,用一种更有趣的方式做事,你可以利用Tailwind的主题化功能。

在这个视频中有很好的解释:https://www.youtube.com/watch?v=MAtaT8BZEAo.

然后你可以更新你的CSS变量与任何颜色是来自你的API我猜。祝你顺利破解:)

参考:用Javascript更新CSS变量:https://css-tricks.com/updating-a-css-variable-with-javascript/

最新更新