You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS自定义Hook组件问题:无法关闭展开项+过渡动画失效

解决NextJS折叠面板的两个问题:手动关闭与过渡失效

问题1:无法手动关闭当前展开模块

原因:自定义Hook的open函数仅直接设置选中章节名,未判断当前是否已打开该章节,导致点击已展开按钮无法触发关闭逻辑。

修改后的自定义Hook:

import { SetStateAction, useState } from "react";

export default function useOpen() {
  const [isOpened, setIsOpened] = useState("closed");
  const open = (sectionName: SetStateAction<string>) => {
    // 当前已打开目标章节则切换为关闭状态,否则打开目标章节
    setIsOpened(prev => prev === sectionName ? "closed" : sectionName);
  };
  return { isOpened, open };
}

问题2:过渡类duration-1000无效果

原因:当前用isOpened === item.chapter && <div/>的条件渲染会直接在DOM中添加/移除元素,而过渡效果需要元素始终存在,通过样式变化触发。

修改后的组件代码:

export default function Opendiv({ item }) {
  const { isOpened, open } = useOpen();
  const isExpanded = isOpened === item.chapter;

  return (
    <div>
      <button type="button" onClick={() => open(item.chapter)}>
        {item.chapter}
      </button>
      {/* 元素始终存在,通过max-height和opacity控制显示隐藏,触发过渡 */}
      <div 
        className={`transition-all duration-1000 ease-in-out overflow-hidden ${
          isExpanded ? "max-h-96 opacity-100" : "max-h-0 opacity-0"
        }`}
      >
        Opened div, opened div, opened div
      </div>
    </div>
  );
}

说明:

  • 用max-h-0和max-h-96(可根据内容高度调整)控制容器高度,overflow-hidden防止内容溢出
  • 配合opacity变化增强过渡视觉效果
  • 元素始终保留在DOM中,样式变化时即可触发Tailwind的过渡动画

内容的提问来源于stack exchange,提问作者Boq7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 15:32:07