如何在 TailwindCSS 中根据同级 div 应用 CSS 过渡

how to apply CSS-transition depending on sibling div in TailwindCSS

提问人:Ali 提问时间:10/18/2023 更新时间:10/18/2023 访问量:18

问:

当我单击“item.title”时,“item.text”将打开。这效果很好。但是我在“item.text”上应用的过渡在打开时不起作用。因此,当我单击“item.title”时,“item.title”应该会随着此转换打开。

  return (
    <div
      className="flex-col border-b-2 border-slate-100"
    >
      <div
        onClick={handleSetIsOpen}
        className="px-5 pt-3 pb-2 font-bold cursor-pointer"
      >
        {item.title}
      </div>
      <div
        className={`px-3 pb-3 ${
          isOpen ? "opacity-100 max-h-screen transition duration-500 ease-in-out" : "hidden opacity-0 max-h-0 transition-all duration-500 ease-in-out"
        }`}
      >
        {item.text}
      </div>
    </div>
  );

我将过渡传递给父 div,但“item.title”也将提供此过渡。但我不想要这个。此转换应仅适用于“item.title”。

reactjs 顺风 css css 过渡

评论


答:

1赞 Wongjn 10/18/2023 #1

CSS 过渡不会发生在应用或删除时的同一帧上。因此,请考虑完全删除该类:display: nonehidden

const { useState } = React;

function App() {
  const [isOpen, setIsOpen] = useState(false);
  
  const handleSetIsOpen = () => {
    setIsOpen(value => !value);
  };
  
  const item = {
    title: 'Foo',
    text: 'bar',
  };
  
  return (
    <div
      className="flex-col border-b-2 border-slate-100"
    >
      <div
        onClick={handleSetIsOpen}
        className="px-5 pt-3 pb-2 font-bold cursor-pointer"
      >
        {item.title}
      </div>
      <div
        className={`px-3 pb-3 ${
          isOpen ? "opacity-100 max-h-screen transition duration-500 ease-in-out" : "opacity-0 max-h-0 transition-all duration-500 ease-in-out"
        }`}
      >
        {item.text}
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('app')).render(<App/>);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js" integrity="sha512-8Q6Y9XnTbOE+JNvjBQwJ2H8S+UV4uA6hiRykhdtIyDYZ2TprdNmWOUaKdGzOhyr4dCyk287OejbPvwl7lrfqrQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js" integrity="sha512-MOCpqoRoisCTwJ8vQQiciZv0qcpROCidek3GTFS6KTk2+y7munJIlKCVkFCYY+p3ErYFXCjmFjnfTTRSC1OHWQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdn.tailwindcss.com/3.3.3"></script>

<div id="app"></div>