如何使用this关键字实现各Section独立展开/收起?
解决多个Section独立展开/收起的问题
你不需要用this——问题根源是所有Section共用了同一个open状态变量,所以点击任意按钮都会触发全局状态变化,导致所有Section同步展开/收起。下面给两种实用的解决方法:
方法一:父组件维护各Section的展开状态
通过对象记录每个Section的独立状态,点击时只切换对应Section的状态:
import { useState } from 'react'; export default function Expand() { // 用对象存储每个Section的展开状态,初始为空(默认都收起) const [openSections, setOpenSections] = useState({}); // 切换指定索引的Section状态 const toggleSection = (sectionIndex) => { setOpenSections(prevState => ({ ...prevState, [sectionIndex]: !prevState[sectionIndex] })); }; return ( <div> {sections.map((item, i) => ( <div key={i}> <button onClick={() => toggleSection(i)}> <h2>{item.heading}</h2> </button> {/* 只渲染当前Section对应的展开内容 */} {openSections[i] && <div>Text when you open</div>} </div> ))} </div> ); }
方法二:拆分为独立的Section子组件
把每个Section封装成独立组件,让每个组件自己维护展开状态,逻辑更解耦,代码更清晰:
import { useState } from 'react'; // 独立的Section子组件 function Section({ heading }) { const [open, setOpen] = useState(false); const toggleOpen = () => { setOpen(!open); }; return ( <div> <button onClick={toggleOpen}> <h2>{heading}</h2> </button> {open && <div>Text when you open</div>} </div> ); } // 父组件 export default function Expand() { return ( <div> {sections.map((item, i) => ( <Section key={i} heading={item.heading} /> ))} </div> ); }
两种方法对比:
- 方法一适合需要在父组件统一控制所有Section状态的场景(比如一键全部展开/收起);
- 方法二更符合组件化思想,每个Section独立可控,推荐日常使用。
内容的提问来源于stack exchange,提问作者Boq7
相关产品推荐
相关产品推荐

