每次我最終都會在className之外使用style屬性,因為下面的範例都無法將樣式套用到我的React元素。你能解釋為什麼會發生這種情況以及我如何解決這個問題嗎?
我已經閱讀了文件(https://tailwindcss.com/docs/content-configuration#dynamic-class-names),但我的使用情況是:使用者從顏色選擇器中選擇顏色,然後我根據選擇的顏色更改背景。我無法將"bg-[colorValue]"的值傳遞給每個單獨的顏色,所以我必須在之後將該值與"bg-["連接起來。因為我無法將所有顏色映射到完整的類別名稱。
const red500 = "red-500"; const red600Hex = "#dc2626"; const bgColor = "bg-[" + red600Hex + "]"; const bgColor2 = "bg-[" + "#dc2626" + "]"; function App() { return ( <> <h1 className={` bg-${red500} `}>Hello</h1> <h1 className={` bg-[${red600Hex}] `}>Hello</h1> <h1 className={` bg-${`[${red600Hex}]`} `}>Hello</h1> <h1 className={` ${bgColor} `}>Hello</h1> <h1 className={` ${bgColor2} `}>Hello</h1> </> ); }
P粉3099896732023-07-19 10:57:55
当模板字面量字符串正常工作时,您无需担心字符串拼接问题。
const red500 = 'red-500'; const red600Hex = '#dc2626'; const bgColor = `bg-[${red600Hex}]`; const bgColor2 = `bg-[${'#dc2626'}]`; export function App() { return ( <> <h1 className={` bg-${red500} `}>Hello</h1> <h1 className={` bg-[${red600Hex}] `}>Hello</h1> <h1 className={` bg-${`[${red600Hex}]`} `}>Hello</h1> <h1 className={` ${bgColor} `}>Hello</h1> <h1 className={` ${bgColor2} `}>Hello</h1> </> ); }
上面的链接还给了我一个关于拼接的警告:"Bug Finder: Unexpected string concatenation of literals.eslint"
我甚至添加了一个选项来动态控制最后一个 h1 的颜色,通过状态来实现:
const colors = [ {value: "#dc2626"}, {value: "#dc06e6"}, {value: "#dce606"}, ] export function App() { const [color, setColor] = React.useState(colors[0].value) return ( <> <h1 className={`text-green-500 bg-${red500} `}>Hello</h1> <h1 className={`bg-[${red600Hex}] `}>Hello</h1> <h1 className={`text-green-200 bg-${`[${red600Hex}]`} `}>Hello</h1> <h1 className={`${bgColor} `}>Hello</h1> <h1 className={`bg-[${color}]`}>Hello</h1> <select onChange={(e) => setColor(e.currentTarget.value)}> {colors.map(c => <option className={`bg-[${c.value}]`} value={c.value}>{c.value}</option>)} </select> </> ); }