我试图在反应中动态更改自定义切换按钮的值,但它没有改变,似乎问题出在 after:content-[] 它接受静态值,但通过传递动态值将不起作用,下面是我的组件代码...
function ToggleOnSteroid({changeType, type1, type2}) {
return (
<div className="w-full">
<label className="relative w-full inline-flex items-center cursor-pointer">
<input className="sr-only peer " value="" type="checkbox" onChange={(e)=>{
if(e.target.checked){
changeType(type1.toLowerCase().replaceAll(' ','-'));
}else{
changeType(type2.toLowerCase().replaceAll(' ','-'));
}
}}/>
<div
className={`peer rounded-md outline-none duration-100 after:duration-500 w-full h-[52px] bg-white border border-gray-300 peer-focus:outline-none peer-focus:ring-2 peer-focus:ring-[#B5A352]
after:content-["Ac"]
after:absolute after:outline-none after:rounded-md after:h-[44px] after:w-[120px] after:bg-[#B5A352] after:top-1 after:left-1 after:flex after:justify-center after:items-center after:text-white after:font-bold peer-checked:after:translate-x-24
peer-checked:after:content-["${type2}"]
peer-checked:after:border-white`}
>
</div>
</label>
</div>
)
}
以下部分有效,
after:content-["Ac"]
但这行不通
after:content-["${type2}"]
像一些新的格式化方法这样的解决方案来解决这个问题
这从根本上就是 Tailwind 的工作原理,您无法动态形成字符串。它们都需要在构建时提前了解。您需要始终形成完整的类名称,并在它们之间切换。
// DON'T
<div class="text-{{ error ? 'red' : 'green' }}-600"></div>
// DO
<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>
如何处理这个问题有点取决于
type2
是什么;如果是工会,您可以轻松执行上述操作。
请参阅 Tailwind 的文档。