React.js实现Collapsibles手风琴时第2项激活后内容不显示问题求助
问题原因排查
- 核心错误:你使用全局的
document.querySelector(".content")查询DOM元素,该方法只会返回整个文档中第一个匹配.content类的节点,也就是永远只能操作Section 1的内容区域,Section 2的内容节点永远不会被选中修改高度,所以点击Section 2时只有标题的激活状态切换,内容区域没有样式变化。 - 其他潜在问题:
- 多个
useEffect未填写依赖数组,会在组件每次渲染时重复执行,造成不必要的性能损耗 - resize事件监听的清理逻辑错误:
addEventListener和removeEventListener传入的是不同的匿名函数引用,导致事件监听器无法被正常卸载,会造成内存泄漏 - 多个
useEffect逻辑重复,可以合并优化
- 多个
修复方案
修改components/Accordition.js文件代码如下:
import { useState, useEffect, useRef } from 'react'; const Accordition = ({ title, children }) => { const [isActive, setIsActive] = useState(false); // 用useRef绑定当前组件的content节点,不会查询到其他组件的元素 const contentRef = useRef(null); const toggleCollapseContent = () => { setIsActive(!isActive); }; // 提取resize处理函数,保证添加和移除的是同一个函数引用 const handleResize = () => { if (!contentRef.current) return; if (isActive) { contentRef.current.style.maxHeight = contentRef.current.scrollHeight + "px"; } else { contentRef.current.style.maxHeight = null; } }; // 合并所有逻辑到同一个useEffect useEffect(() => { handleResize(); window.addEventListener("resize", handleResize); // 清理函数 return () => { window.removeEventListener("resize", handleResize); }; // 依赖填写完整 }, [isActive]); return ( <div className="lp-collapsible-content"> <div className={`title ${isActive ? "active" : ""}`} onClick={toggleCollapseContent} > {title} </div> {/* 给content节点绑定ref */} <div ref={contentRef} className="content">{children}</div> </div> ); }; export default Accordition;
内容的提问来源于stack exchange,提问作者Kim Duyến
相关产品推荐
相关产品推荐

