动态添加时,Tailwind 的背景颜色不会被应用

Tyl*_*les 16 reactjs tailwind-css

我正在尝试使用 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>
          )
      })
    }
      
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)

小智 29

在 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>
      )
    }
      
    </>
  );
}
Run Code Online (Sandbox Code Playgroud)