[英]How to add a style on a condition in tailwind css
I am making a Side Nav in React using tailwind css I have to add border-red color when a particular link is selected. 所以我正在使用这种方法但这不起作用任何人都可以在这里帮助我
<li className={"flex items-center space-x-2 px-4 py-5 transition duration-500 ease-in-out transform hover:-translate-y-1 hover:scale-110 border-l-4 border-white" + (window.location.pathname === '/' ? 'border-red-200' : '')}>
<NavLink to={"/"}>
<div className="sidebar">
<div className="float-left">
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-8 w-6 text-red-400"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"
/>
</svg>
</div>
<span className="text-2xl float-right pl-5">
Home
</span>
</div>
</NavLink>
</li>
使用模板文字,或使用 npm 库类名。
<... className={`flex items-center space-x-2 px-4 py-5 transition duration-500 ease-in-out transform hover:-translate-y-1 hover:scale-110 border-l-4 border-white ${window.location.pathname === '/' ? 'border-red-200' : ''}`}>
import classNames from 'classnames';
<... className={classNames('flex items-center space-x-2 px-4 py-5 transition duration-500 ease-in-out transform hover:-translate-y-1 hover:scale-110 border-l-4 border-white',
{
'border-red-200': window.location.pathname === '/'
}
)}>
对于 NavLink 组件,您可以在链接处于活动状态时使用 activeStyle 属性应用 styles。
<NavLink
to="/"
activeStyle={{
border-bottom: "2px solid red";
}}
>
Link Name
</NavLink>
className={yourItem === value ? 'your-class' : 'or-default-to'}
` /* 如果您的设置条件为真,则应用类。 下面的例子*/
className={active === value ? 'text-green' : 'text-white'}
class={active === value ? 'text-green' : 'text-white'}
对我来说,使用类名库是具有多种条件的最干净的方法:
从“类名”导入 cx;
const classes = cx(
'flex items-center justify-center', // classes that should be used in any case
size === 'small' && 'h-10 text-lg px-2.5',
size === 'medium' && 'h-12 text-lg px-4',
variant === 'primary text-primary`,
variant === 'secondary text-secondary`,
fullWidth && 'w-full',
className // classname passed from props
);
但在你的情况下,字符串插值就足够了
`flex items-center space-x-2 px-4 py-5 transition duration-500 ease-in-out transform hover:-translate-y-1 hover:scale-110 border-l-4 border-white ${window.location.pathname === '/' ? 'border-red-200' : ''}`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.