ReactJS/NextJS中View More按钮批量展开问题求助
解决多区域独立控制View More展开/收起的问题
问题根源
你当前的代码使用全局共享状态(currentSliceStartEx、currentSliceEndEx)控制所有区域的内容显示范围,导致点击任意区域的View More按钮时,所有区域都会同步切换展开/收起状态——因为它们都依赖同一组全局state值。
解决方案
给每个区域分配独立的状态,用对象记录各区域的展开状态(key为区域名称,value为布尔值表示是否展开),确保单个区域的状态变化不会影响其他区域。
修改后的完整代码
"use client"; import React, { useState } from "react"; export default function Result() { const data = { "data": { "sec1": ["my sisters and brothers are near and dear","near neighbors","in the near future","they are near equals","his nearest approach to success","a very near thing","a near hit by the bomb","she was near tears","the near or nigh horse is the one on the left","the animal's left side is its near or nigh side","a near likeness","very close (or near) with his money","near beer","a dress of near satin"], "sec2": ["as the wedding day drew near","stood near the door","don't shoot until they come near","getting near to the true explanation","her mother is always near","he nearly fainted","I was near exhausted by the run"], "sec3": ["They are drawing near","The enemy army came nearer and nearer"] } }; // 用对象存储每个区域的独立展开状态 const [expandedSections, setExpandedSections] = useState({ sec1: false, sec2: false, sec3: false }); // 仅切换指定区域的展开状态 const toggleExpand = (sectionName) => { setExpandedSections(prevState => ({ ...prevState, [sectionName]: !prevState[sectionName] })); }; const InnerContent = ({ item }) => ( <div className="container"> <p>{item}</p> </div> ); const MainContent = ([sectionName, contentList]) => { // 根据当前区域的展开状态决定显示范围 const displayItems = expandedSections[sectionName] ? contentList : contentList.slice(0, 2); // 仅当内容数量超过2条时显示切换按钮 const showToggleBtn = contentList.length > 2; return ( <div key={sectionName}> <p className={`my-7 sec-${sectionName}`}> As a {sectionName} </p> {displayItems.map((item, idx) => ( <InnerContent key={idx} item={item} /> ))} {showToggleBtn && ( <span className="cursor-pointer" onClick={() => toggleExpand(sectionName)} > View {expandedSections[sectionName] ? "less" : "more"} </span> )} </div> ); }; return ( <> {data?.data && Object.entries(data.data).map(MainContent)} </> ); }
关键改动说明
- 状态拆分:将全局切片状态替换为
expandedSections对象,每个区域独立维护自身的展开状态,避免跨区域干扰。 - 切换逻辑优化:
toggleExpand函数仅修改指定区域的状态,不影响其他区域的显示。 - 内容渲染独立:每个区域根据自身的展开状态决定显示全部内容或前2条,不再依赖全局统一的切片值。
- 按钮显示逻辑:仅当内容数量超过2条时才显示切换按钮,并根据当前状态动态切换按钮文字。
内容的提问来源于stack exchange,提问作者Kevin
相关产品推荐
相关产品推荐

