[英]Render a specific className when active with classNames and Tailwind
I'm using Tailwinds CSS and classNames package.我正在使用Tailwinds CSS和classNames包。
I'm rendering out 2 div
s and I want to check if one of them has am active
class, then set a specific background color className bg-[#000]
to it.我正在渲染 2 个
div
并且我想检查其中一个是否有active
类,然后为其设置特定的背景颜色 className bg-[#000]
。
'bg-[#000]': 'active'
check but this just inserts the background color on all elements.'bg-[#000]': 'active'
check 但这只是在所有元素上插入背景颜色。 How can we set a specific style to an active element with Tailwind
and classNames
?我们如何使用
Tailwind
和classNames
为活动元素设置特定样式?
Thank you!谢谢!
Screenshots:截图:
Here's a screenshot of the tags, the 1st one is currently active.这是标签的屏幕截图,第一个当前处于活动状态。 But the second one which is not active also has the
bg-[#000]
class.但是第二个不活跃的也有
bg-[#000]
类。
Code:代码:
list.map((page, index) => {
return (
<div
key = {index}
onClick = {() => setCurrentListIdx(index)}
className = {
classNames('bullets__item m-1.5 h-2 w-2 cursor-pointer rounded-full bg-[#e0e0e0]',
{
active: currentListIdx === +index,
'bg-[#000]': 'active',
}
)}
></div>
)
})
In the conditional 'bg-[#000]': 'active'
, you're passing the string 'active'
rather than a variable or an expression to evaluate.在条件
'bg-[#000]': 'active'
中,您传递的是字符串'active'
而不是要评估的变量或表达式。 This is returning true
because JS strings are truthy, and so always adding the class.这将返回
true
,因为 JS 字符串是真实的,因此总是添加类。 The classNames
utility doesn't appear to allow checking against currently applied class names in its conditionals object this way. classNames
实用程序似乎不允许以这种方式检查其条件对象中当前应用的类名。
You could alternatively use the same conditional for both class names: currentListIdx === +index
, so both classes would be added when this condition is met.您也可以对两个类名使用相同的条件:
currentListIdx === +index
,因此在满足此条件时将添加两个类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.