当与ClassName和tailwind一起活动时,呈现一个特定的className

发布于 2025-02-12 05:16:05 字数 1085 浏览 1 评论 0原文

我正在使用 tailwinds css classNames 软件包。

我正在渲染2 div s,我想检查其中一个是否具有AM 活动类,然后设置特定的背景颜色className bg- [# 000]

  • 我尝试使用'BG - [#000]':'Active'检查,但这只是在所有元素上插入背景颜色。

我们如何使用tailwindclassNames将特定样式设置为活动元素?

谢谢你!

屏幕截图:

这是标签的屏幕截图,第一张标签当前处于活动状态。 但是第二个不活动的一个也具有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 divs 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.

enter image description here

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深爱不及久伴 2025-02-19 05:16:05

在条件'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 returning true because JS strings are truthy, and so always adding the class. The classNames 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文