顺风颜色在更改时不显示

Tailwind colors doesnt display when changed

我得到了一个数组,其中的颜色已经在 tailwind 默认调色板中定义,如下所示

colors: ["red-600", "blue-600", "pink-600", "black", "white", "yellow-600"]

我映射数组以生成具有数组中定义的背景颜色的小框。

{colors.map((col, i) => (
        <button
          className="cursor-pointer"
          key={i}
        >
          <div
            className={`mt-3 border-2 border-solid border-black bg-${col} w-8 h-8`}
          >

我的问题是如果我更改数组中的任何颜色(比如将 red-600 更改为 red-900)它不会显示,尽管这两种颜色都在默认调色板中定义

这里可能有什么问题?

首先,你应该将颜色数组设置为state,当这个数组改变时,这个组件将re-render。

Second,如果只在colors array内改变,它不会强制这个组件re-render读取你的状态改变,所以你应该添加强制组件 re-render 的另一种状态,例如 [forceChangeColor, setForceChangeColor] = useState(0):

const [colors, setColors] = useState(["red-600", "blue-600", "pink-600", "black", "white", "yellow-600"])
const [forceChangeColor, setForceChangeColor] = useState(0)

const handleChangeColor = () => {
  setColors([/*set your change colors*/]) // <=== set Colors change in here
  setForceChangeColor(prev => prev + 1) //<=== Make another state change to force this component re-render to re-read colors state
}


{colors.map((col, i) => (
        <button
          className="cursor-pointer"
          key={i}
        >
          <div
            className={`mt-3 border-2 border-solid border-black bg-${col} w-8 h-8`}
          >
        

我曾在尝试与您当前正在尝试的事情非常相似的事情时遇到过这个问题...我意识到您不能将 Tailwind 值部分设置为变量,而必须是整个值如果您要为其使用变量。

示例:

make an array strictly for bg-colors

bgColors: [
  "bg-red-600",
  "bg-blue-600", 
  "bg-pink-600", 
  "bg-black", 
  "bg-white", 
  "bg-yellow-600"
]

and now you should be able to use them as variables with the whole value instead of a partial value.

className={`${col}`} // ${col} === bg-color-###