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

React组件点击按钮仅展示对应容器描述的实现问题

问题:点击描述按钮仅显示对应容器的描述

当前点击Descripcion按钮后,所有通过map渲染的容器都显示了各自的描述,希望实现仅展示被点击容器对应ID的描述。

问题分析

当前代码使用布尔类型的showDescripcion状态,点击按钮后会将这个状态设为true,导致所有列表项的描述部分都被渲染;同时normal状态也是全局控制所有项的显示切换,这显然不符合“仅显示对应项”的需求。

解决方案

将状态改为存储当前选中的服务ID(初始值设为null),通过判断当前服务的ID是否与选中ID匹配,来控制对应项的显示状态。具体修改如下:

修改后的代码

import { useState } from "react";

export default function ServiciosCard({ profile }) {
  // 存储当前选中的服务ID,初始值为null表示未选中任何服务
  const [selectedServiceId, setSelectedServiceId] = useState(null);

  const showDescripcionChangeHandler = (serviceId) => {
    // 点击已选中的ID则取消选中,否则设置为当前ID
    setSelectedServiceId(prevId => prevId === serviceId ? null : serviceId);
  };

  return (
    <>
      <div
        className=" space-y-4 mt-3 md:mt-0 h-[450px] md:h-[550px] overflow-y-auto
     md:scrollbar scrollbar-track-[#d0e7d5] scrollbar-thumb-[#ef8eb2]
  text-center "
      >
        {profile.servicios.map((servicio) => (
          <div key={servicio._id}>
            {/* 未选中当前服务时,显示默认卡片 */}
            {selectedServiceId !== servicio._id && (
              <div
                className="bg-[#f7ede2] rounded-md w-[300px] h-[75px] "
              >
                <div>{servicio.unServicio}</div>
                <div>1 Hr {servicio.costo}</div>
                <div className=" space-x-4">
                  <button className="text-[#f77f00] hover:headerButton">
                    Reserva ahora
                  </button>
                  {/* 用箭头函数绑定事件,避免组件挂载时立即执行 */}
                  <button
                    onClick={() => showDescripcionChangeHandler(servicio._id)}
                    className="text-[#f77f00] hover:headerButton"
                  >
                    Descripcion
                  </button>
                </div>
              </div>
            )}
            {/* 选中当前服务时,显示描述 */}
            {selectedServiceId === servicio._id && (
              <div
                className="bg-[#f7ede2] rounded-md w-[300px] h-[75px] "
              >
                {servicio.description}
              </div>
            )}
          </div>
        ))}
      </div>
    </>
  );
}

关键修改点

  • 状态逻辑优化:合并showDescripcion和normal状态为selectedServiceId,通过存储选中ID实现精准控制单个项的显示状态。
  • 点击事件修复:将直接调用函数的写法改为箭头函数,避免组件渲染时立即执行事件处理函数。
  • 显示条件调整:通过对比selectedServiceId与当前服务的_id,实现点击哪项就只显示哪项的描述,再次点击可切换回默认视图。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:05:17