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

遍历数组时如何实现单个元素的编辑区域独立触发?

解决点击编辑按钮后所有下拉区域同时显示的问题

我正在遍历数组展示数据,给每条数据都加了编辑按钮,点击按钮会弹出对应的下拉编辑区域。现在遇到的问题是,点击任意一个编辑按钮时,所有条目的编辑区域都会同时显示,我希望只有被点击按钮对应的那一个区域展开,请问该怎么实现?

原代码:

const [show, setShow] = useState(false);
const handleShow = () => { setShow(!show); };

<p onClick={handleShow}>
  Edit
  {show === true ? (
    <IoIosArrowUp style={{ color: "#F1BB0F" }} />
  ) : (
    <IoIosArrowDown style={{ color: "#F1BB0F" }} />
  )}
</p>

{show && (
  <div>
    <p>
      Unlocks: {lockParams[index]?.endDateString}
    </p>
    <p>
      Unlocker : <span>{lockParams[index]?.unlocker}</span>
    </p>
  </div>
)}

解决方案:

问题出在你用了单个布尔值show控制所有条目的显示状态,点击按钮时这个状态会统一切换,导致所有区域同步变化。要实现单个条目独立控制,只需要把状态改成存储当前展开条目的索引即可:

  • 修改状态定义:
    把单个布尔值换成存储索引的状态,初始值设为null(表示没有条目展开):
const [activeIndex, setActiveIndex] = useState(null);
  • 修改点击事件函数:
    让函数接收当前条目的索引,点击时判断如果当前索引已经是展开状态,就关闭它;否则切换到当前索引:
const handleShow = (index) => {
  setActiveIndex(prevIndex => prevIndex === index ? null : index);
};
  • 更新渲染逻辑:
    按钮的箭头和下拉区域的显示,都改成判断当前条目索引是否等于activeIndex:

修改后的完整渲染代码(结合数组遍历):

// 状态定义
const [activeIndex, setActiveIndex] = useState(null);

// 点击处理函数
const handleShow = (index) => {
  setActiveIndex(prevIndex => prevIndex === index ? null : index);
};

// 遍历lockParams数组渲染条目
{lockParams.map((item, index) => (
  <div key={index}>
    <p onClick={() => handleShow(index)}>
      Edit
      {activeIndex === index ? (
        <IoIosArrowUp style={{ color: "#F1BB0F" }} />
      ) : (
        <IoIosArrowDown style={{ color: "#F1BB0F" }} />
      )}
    </p>

    {activeIndex === index && (
      <div>
        <p>
          Unlocks: {item?.endDateString}
        </p>
        <p>
          Unlocker : <span>{item?.unlocker}</span>
        </p>
      </div>
    )}
  </div>
))}

这样修改后,点击某个条目编辑按钮时,只有该条目对应的下拉区域会展开/收起,其他条目不受影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:33:26