如何在tailwindcss中使用模板文字来动态更改类?

IT技术 css reactjs templates next.js tailwind-css
2021-04-29 06:57:59

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

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>;
1个回答

像这样做:

<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>

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

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

相反,您可以选择完整的类名:

<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>

只要类名完整地出现在您的模板,Tailwind 就不会将其从生产版本中删除。


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

进一步阅读: