如何使用 TailwindCSS 和 React 有条件地添加/删除类

Ken*_*nce 1 reactjs tailwind-css tailwind-in-js

我有一个表达式,用于查找表单错误并在出现冒泡时附加一个 div:

\n
{touched && normalizedError && (\n      <div className="visible alert-error text-xs text-red-500" role="alert">\n        {normalizedError}\n      </div>\n    )}\n
Run Code Online (Sandbox Code Playgroud)\n

我想重构它并始终在我的输入元素下方显示 div,但使用该类invisble对用户隐藏它们,除非返回错误\xe2\x80\x94,在这种情况下,我将有条件添加该类visible

\n

实现这一目标的最佳方法是什么?

\n

lui*_*ero 7

有多种方法可以实现您想要的效果,最简单的方法是在 className 本身中添加条件

<div className={`alert-error text-xs text-red-500 ${touched && normalizedError ? 'visible' : 'invisible'}`}  role="alert">
  {normalizedError}
</div>

Run Code Online (Sandbox Code Playgroud)