当与ClassName和tailwind一起活动时,呈现一个特定的className
我正在使用 tailwinds css 和 classNames 软件包。
我正在渲染2 div
s,我想检查其中一个是否具有AM 活动
类,然后设置特定的背景颜色className bg- [# 000]
。
- 我尝试使用
'BG - [#000]':'Active'
检查,但这只是在所有元素上插入背景颜色。
我们如何使用tailwind
和classNames
将特定样式设置为活动元素?
谢谢你!
屏幕截图:
这是标签的屏幕截图,第一张标签当前处于活动状态。 但是第二个不活动的一个也具有bg - [#000]
类。
代码:
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>
)
})
I'm using Tailwinds CSS and classNames package.
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.
- I tried using
'bg-[#000]': 'active'
check but this just inserts the background color on all elements.
How can we set a specific style to an active element with Tailwind
and 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.
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>
)
})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在条件
'BG - [#000]':'Active'
中,您正在传递字符串'Active'
而不是变量或表达式以进行评估。这是返回true
,因为JS字符串是真实的,因此始终添加类。classNames
公用事业似乎不允许对当前应用的类名称进行检查在其条件上以这种方式对象。您也可以使用两个类名称使用相同的条件:
currentListIdx === +index
,因此在满足此条件时将添加两个类。In the conditional
'bg-[#000]': 'active'
, you're passing the string'active'
rather than a variable or an expression to evaluate. This is returningtrue
because JS strings are truthy, and so always adding the class. TheclassNames
utility doesn't appear to allow checking against currently applied class names in its conditionals object this way.You could alternatively use the same conditional for both class names:
currentListIdx === +index
, so both classes would be added when this condition is met.