如何在不使用 JavaScript 的情况下使用 Tailwindcand 对非嵌套非同级级联单选按钮组进行分组和切换?

问题描述 投票:0回答:1

因此,我正在为我们的新网站使用 Next.js 14 React Server Components 等技术,并且我尝试尽可能多地使用服务器组件 - 至少在我绝对必须将某些功能转移到客户端之前组件。

这意味着我想坚持“CSS”领域,并选择退出 JavaScript 来处理一些琐碎的事情,其中 JS 并不真正需要,但经常使用,因为它更容易或我们已经习惯了。

给我带来问题的是我们也在使用的 Tailwind。我能够通过以下方式使用纯 CSS 快速解决我的问题:

.times {
  display: none;
}

.timeslots:has(.timeslot-1 > input:checked)~.timeslot-1-times {
  display: block;
}

.timeslots:has(.timeslot-2 > input:checked)~.timeslot-2-times {
  display: block;
}

.timeslots {
  display: flex;
  gap: 1rem;
}
<form>
  <div>
    <div class="timeslots">
      <div class="timeslot-1">
        <input type="radio" name="date" id="2024-04-28" />
        <label for="2024-04-28">2024-04-28</label>
      </div>
      <div class="timeslot-2">
        <input type="radio" name="date" id="2024-04-29" />
        <label for="2024-04-29">2024-04-29</label>
      </div>
    </div>
    <div class="times timeslot-1-times">
      <div>
        <input type="radio" name="time" id="12" />
        <label for="12">12</label>
      </div>
      <div>
        <input type="radio" name="time" id="13" />
        <label for="13">13</label>
      </div>
    </div>
    <div class="times timeslot-2-times">
      <div>
        <input type="radio" name="time" id="15" />
        <label for="15">15</label>
      </div>
    </div>
  </div>
</form>

如果“时间”嵌套在每个日期下,那么使用顺风车

peer
peer-checked
甚至使用检查的伪选择器来解决这将是微不足道的。然而,我确实需要在水平列表中呈现日期,并在下面以全角显示每个日期的时间,就像我试图在上面的代码片段中显示的典型选项卡组件一样。

一般来说,我希望在使用 tailwind 时避免使用纯 css,因为创建者表示,如果他能及时返回,他会删除“@apply”。那么,实现与上面的代码片段类似的功能的最佳实践 Tailwind-way 是什么?我是否缺少一种简单的内置方式,或者我需要添加自己的自定义变体?

tailwind-css
1个回答
0
投票

您可以使用

peer-has-*
修饰符 来模拟普通 CSS,以有条件地应用
display: block
:

<script src="https://cdn.tailwindcss.com/3.4.3"></script>

<form>
  <div>
    <div class="flex gap-4 peer">
      <div class="timeslot-1">
        <input type="radio" name="date" id="2024-04-28" />
        <label for="2024-04-28">2024-04-28</label>
      </div>
      <div class="timeslot-2">
        <input type="radio" name="date" id="2024-04-29" />
        <label for="2024-04-29">2024-04-29</label>
      </div>
    </div>
    <div class="hidden peer-has-[.timeslot-1>input:checked]:block">
      <div>
        <input type="radio" name="time" id="12" />
        <label for="12">12</label>
      </div>
      <div>
        <input type="radio" name="time" id="13" />
        <label for="13">13</label>
      </div>
    </div>
    <div class="hidden peer-has-[.timeslot-2>input:checked]:block">
      <div>
        <input type="radio" name="time" id="15" />
        <label for="15">15</label>
      </div>
    </div>
  </div>
</form>

© www.soinside.com 2019 - 2024. All rights reserved.