我正在尝试使用Tailwind设置动态背景色。
但是,背景色未应用于div。我很困惑,因为当我检查检查器时,我可以看到在浏览器中,正确的bg-${colors[index]}应用于每个div,但颜色没有被渲染。
const colors = ['#7a5195', '#bc5090','#ef5675']
export default function App() {
const names = ['Tyler', "Charles", 'Vince']
let labels = {}
names.forEach((name,index)=>{
labels[name] = `bg-[${colors[index]}]`
})
return (
<>
{
names.map((name)=>{
return(
<div className={`${labels[name]}`}>
{name}
</div>
)
})
}
</>
);
}
3条答案
按热度按时间dgsult0t1#
在Tailwind中,你不能像
bg-${color}
那样使用动态类命名。这是因为当Tailwind编译CSS时,它会查找所有代码并检查类名是否匹配。
如果你想动态命名类,你应该写所有的类名。
但对于您的特定用例,我不会使用Tailwind的JIT,而是使用
style
属性并动态更改backgroundColor
值。它将使用更少的CSS,也给予你更少的头痛。
最后,这是我的建议
3qpi33ja2#
你也可以在你的顺风配置中添加类到你的安全列表中。
通过这种方式,您可以动态使用colorClasses数组中包含的颜色,因为它们不会被清除。
注意:例如,如果你想做bg-blue-500,你需要包括所有的颜色权重作为安全列表的一部分(以及将该颜色添加到数组中)。
bbuxkriu3#
试试这个代码