动态添加时未应用顺风的背景色



我正在尝试使用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>
)
})
}

</>
);
}

在Tailwind中你不能像bg-${color}那样使用动态类命名

这是因为当Tailwind编译它的CSS时,它会查找你所有的代码并检查类名是否匹配。

如果你想动态命名类,你应该写所有的类名。

但是对于您的特定用例,我不会使用Tailwind的JIT,而是使用style属性并动态更改backgroundColor值。

它将使用更少的CSS,也给你更少的头痛。

最后,这是我的建议

const colors = ['#7a5195', '#bc5090','#ef5675'];
export default function App() {
const names = ['Tyler', "Charles", 'Vince']
const labels = {};
names.forEach((name, index) => {
labels[name] = colors[index];
});
return (
<>
{
names.map((name) => (
<div style={{ backgroundColor: `${labels[name]}` }}>
{name}
</div>
)
}

</>
);
}

您还可以在顺风配置中将类添加到安全列表中。

// tailwind.config.js
// Create an array for all of the colors you want to use
const colorClasses = [
'#7a5195', 
'#bc5090',
'#ef5675'
];
module.exports = {
purge: {
content: ["./src/**/*.{js,jsx,ts,tsx}", "./public/index.html"],
// Map over the labels and add them to the safelist
safelist: [
...colorClasses.map((color) => `bg-${color}`)
],
},
darkMode: false, // or 'media' or 'class'
variants: {
extend: {},
},
plugins: [require("@tailwindcss/forms")],
}

这样你就可以动态地使用包含在colorClasses数组中的颜色,因为它们不会被清除。

注意:如果你想做bg-blue-500,例如,你需要包括所有的颜色权重作为安全列表的一部分(以及将该颜色添加到数组中)。

...colorClasses.map((color) => `bg-${color}-500`)

试试这个代码

className={`bg-[${color}]`}

最新更新