reactjs 动态添加时未应用Tailwind的背景色

fquxozlt  于 2023-05-06  发布在  React
关注(0)|答案(3)|浏览(151)

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

dgsult0t1#

在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>
      )
    }
      
    </>
  );
}
3qpi33ja

3qpi33ja2#

你也可以在你的顺风配置中添加类到你的安全列表中。

// 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`)
bbuxkriu

bbuxkriu3#

试试这个代码

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

相关问题