问题描述
我试图用这行代码来改变它,但它不起作用
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 就不会将其从生产构建中移除.
还有更多选项可供您使用,例如使用 classnames 或 clsx,或者可能是 Tailwind 特定的解决方案,例如 twin.macro, twind, xwind.
进一步阅读:
- React.js 有条件地应用类名
- 如何在手动类名中动态添加类?
- 在 React 中处理条件样式的正确方法
- 在 JSX 中嵌入表达式
- 模板文字 - MDN
- 生产优化 - 编写可清除的 HTML - Tailwind CSS
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:
- React.js conditionally applying class names
- How to dynamically add a class to manual class names?
- Correct way to handle conditional styling in React
- Embedding Expressions in JSX
- Template literals - MDN
- Optimizing for Production - Writing purgeable HTML - Tailwind CSS
这篇关于如何在 tailwindcss 中使用模板文字动态更改类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!