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

解决MUI动态映射卡片点击后全部隐藏卡片展开的问题

解决方法

问题核心是你用了一个全局布尔状态showContextCard,所有动态生成的卡片共用这个状态,导致点击时所有隐藏卡片同步切换。要实现单张卡片独立控制,需要改成记录当前激活卡片的唯一标识(比如索引或卡片ID)。

具体修改步骤:

  1. 修改状态定义
    把原来的布尔状态改成存储当前激活的卡片索引(如果group有唯一ID,比如group.id,用ID更稳妥),初始值设为null表示无激活卡片:
const [activeContextCardKey, setActiveContextCardKey] = useState(null);
  1. 调整点击事件逻辑
    点击时判断当前激活的是不是当前卡片的标识,是则关闭(设为null),否则激活该标识:
function handleShowContext() {
  setActiveContextCardKey(prev => 
    prev === groupIndex ? null : groupIndex
  );
}
  1. 修改隐藏卡片的显示条件
    只有当当前激活标识等于当前卡片的标识时,才显示隐藏卡片:
<Card hidden={activeContextCardKey !== groupIndex} className={classes.contextCard}>
  Comment Card
</Card>

修改后的完整代码片段

const [activeContextCardKey, setActiveContextCardKey] = useState(null);
...
<Box className={classes.groupCards}>
    {questionGroups?.displaygroups?.ConslutingQuestions &&
    questionGroups?.displaygroups?.ConslutingQuestions?.map((group, groupIndex) => {
        function handleShowContext() {
            setActiveContextCardKey(prev => 
                prev === groupIndex ? null : groupIndex
            );
        }
        return (
            <>
                <Card className={classes.card}>
                    <CardHeader 
                        className={classes.cardTitle} 
                        title={group.GroupName} 
                        subheader={group.OwnerName} 
                        onClick={handleShowContext} {/* 补上点击事件绑定 */}
                    />
                </Card>
                <Card hidden={activeContextCardKey !== groupIndex} className={classes.contextCard}>
                    Comment Card
                </Card>
            </>
        );
    })}
</Box>

补充说明

  • 若group对象有唯一ID(如group.id),建议用ID替代groupIndex,避免数组顺序变化导致的匹配错误。
  • 务必给触发点击的元素(比如CardHeader)绑定onClick事件,否则点击不会生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:05:20