每次我最终都会在 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>
</>
);
}
当 模板文字 字符串工作得很好时,你不必担心字符串连接:
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:文字.eslint 出现意外的字符串连接”
我扩展了上面的内容,用
h1
动态控制最后一个useState
的颜色:
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>
</>
);
}
此用途的一个用例可能是设置组件或站点的主题,例如 Tailwind CSS 站点 具有: