我目前正在使用 TailwindCss 為我的下一個專案構建一個組件庫,我在處理 Button 組件時遇到了一個小問題。
我正在傳遞類似'primary'或'secondary'匹配我在中指定的顏色的道具,tailwind.config.js然后我想使用Template literals如下方式將其分配給按鈕組件:bg-${color}-500
<button
className={`
w-40 rounded-lg p-3 m-2 font-bold transition-all duration-100 border-2 active:scale-[0.98]
bg-${color}-500 `}
onClick={onClick}
type="button"
tabIndex={0}
>
{children}
</button>
類名在瀏覽器中顯示得很好,它顯示bg-primary-500在 DOM 中,但不在應用的樣式選項卡中。

主題配置如下:
theme: {
extend: {
colors: {
primary: {
500: '#B76B3F',
},
secondary: {
500: '#344055',
},
},
},
},
但它不應用任何樣式。如果我只是bg-primary-500手動添加它作業正常。
老實說,我只是想知道這是因為 JIT 編譯器沒有選擇動態類名還是我做錯了什么(或者這不是使用 tailWind 的方式)。
歡迎任何幫助,提前致謝!
uj5u.com熱心網友回復:
不推薦使用這種方式撰寫 Tailwind CSS 類。甚至JIT 模式也不支持它,參考 Tailwind CSS 檔案:“ Tailwind 不包含任何型別的客戶端運行時,因此類名需要在構建時靜態提取,并且不能依賴任何型別在客戶端更改的任意動態值“
uj5u.com熱心網友回復:
所以在發現不推薦這種作業方式并且 JIT 不支持它之后(感謝慷慨的評論者)。我已將方法更改為更基于“配置”的方法。
基本上,我為不同的 props 定義了一個具有基本配置的 const,并將它們應用到組件中。這是更多的維護作業,但它可以完成作業。
這是配置的示例。(目前沒有打字)和一些更好的重構,但你會明白的。
const buttonConfig = {
// Colors
primary: {
bgColor: 'bg-primary-500',
color: 'text-white',
outline:
'border-primary-500 text-primary-500 bg-opacity-0 hover:bg-opacity-10',
},
secondary: {
bgColor: 'bg-secondary-500',
color: 'text-white',
outline:
'border-secondary-500 text-secondary-500 bg-opacity-0 hover:bg-opacity-10',
},
// Sizes
small: 'px-3 py-2',
medium: 'px-4 py-2',
large: 'px-5 py-2',
};
然后我就像這樣應用樣式:
<motion.button
whileTap={{ scale: 0.98 }}
className={`
rounded-lg font-bold transition-all duration-100 border-2 focus:outline-none
${buttonConfig[size]}
${outlined && buttonConfig[color].outline}
${buttonConfig[color].bgColor} ${buttonConfig[color].color}`}
onClick={onClick}
type="button"
tabIndex={0}
>
{children}
</motion.button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/333501.html
