如何在 tailwindcss 中使用模板文字动态更改类? [英] How to use template literals in tailwindcss to change classes dynamically?

查看:29
本文介绍了如何在 tailwindcss 中使用模板文字动态更改类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用这行代码来改变它,但它不起作用

const [click, setClick] = useState(false);const closeNav = () =>{设置点击(!点击);};常量 openNav = () =>{设置点击(!点击);};

解决方案

这样做:

<div className={`absolute inset-0 ${click ?'translate-x-0' : '-translate-x-full'} 变换 z-400 h-screen w-1/4 bg-blue-300`}></div>//或者(没有模板文字):<div className={'absolute inset-0 ' + (click ? 'translate-x-0' : '-translate-x-full') + ' 变换 z-400 h-screen w-1/4 bg-blue-300'}></div>


请记住不要使用字符串连接来创建类名,如下所示:

<div className={`text-${error ?'红色' : '绿色'}-600`}></div>

您可以选择完成类名:

<div className={`${error ?'text-red-600' : 'text-green-600'}`}></div>//如果您不需要连接类名,以下也是有效的<div 类名={错误?'text-red-600' : 'text-green-600'}></div>

只要类名完整地出现在您的模板中,Tailwind 就不会将其从生产构建中移除.


还有更多选项可供您使用,例如使用 classnamesclsx,或者可能是 Tailwind 特定的解决方案,例如 twin.macro, twind, xwind.

进一步阅读:

I tried to change it with this line of code it but it doesn't work

const [click, setClick] = useState(false);

const closeNav = () => {
  setClick(!click);
};

const openNav = () => {
  setClick(!click);
};

<div
  className=" absolute inset-0 ${click ? translate-x-0 : -translate-x-full } 
        transform  z-400 h-screen w-1/4 bg-blue-300 "
>
  <XIcon onClick={closeNav} className=" absolute h-8 w-8 right-0 " />
</div>;

解决方案

Do it like this:

<div className={`absolute inset-0 ${click ? 'translate-x-0' : '-translate-x-full'} transform z-400 h-screen w-1/4 bg-blue-300`}></div>

// Alternatively (without template literals):
<div className={'absolute inset-0 ' + (click ? 'translate-x-0' : '-translate-x-full') + ' transform z-400 h-screen w-1/4 bg-blue-300'}></div>


Just keep in mind not to use string concatenation to create class names, like this:

<div className={`text-${error ? 'red' : 'green'}-600`}></div>

Instead you can select complete class name:

<div className={`${error ? 'text-red-600' : 'text-green-600'}`}></div>

// following is also valid if you don't need to concat the classnames
<div className={error ? 'text-red-600' : 'text-green-600'}></div>

As long as a class name appears in your template in its entirety, Tailwind will not remove it from production build.


There are some more options available for you like using a library like classnames or clsx, or maybe Tailwind specific solutions like twin.macro, twind, xwind.

Further Reading:

这篇关于如何在 tailwindcss 中使用模板文字动态更改类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆