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

MaterialUI Collapse组件循环渲染时批量展开/折叠的问题解决

解决MaterialUI循环渲染时Collapse同步展开/折叠的问题

你当前用单个布尔值expanded控制所有卡片的折叠状态,所以点击任何一个按钮,所有组件都会同步切换。要实现单独控制,核心是把状态改成存储当前展开的卡片ID,而不是单纯的布尔值,具体修改步骤如下:

1. 修改State定义

将原来的布尔值State改为存储ID的变量,初始值设为null(表示没有卡片处于展开状态):

const [expandedId, setExpandedId] = useState(null);

2. 重写点击事件处理函数

直接把当前卡片的RecetasAll.id作为参数传入,逻辑更清晰,避免从事件对象取ID的潜在问题:

const handleExpandClick = (id) => {
  // 逻辑:如果点击的是当前展开的卡片,就收起;否则展开该卡片
  setExpandedId(prevId => prevId === id ? null : id);
};

3. 更新组件的属性绑定

修改ExpandMore和Collapse的属性,判断当前卡片ID是否匹配expandedId:

return (
  <React.Fragment key={RecetasAll.id}>
    <Card className="searchItem" sx={{ maxWidth: 345 }}>
      {/* 原有CardHeader、Dieta、Calorias、CardMedia、CardContent部分保持不变 */}
      <CardActions disableSpacing>
        <IconButton aria-label="add to favorites">
          <FavoriteIcon />
        </IconButton>
        <ExpandMore
          expand={expandedId === RecetasAll.id}
          onClick={() => handleExpandClick(RecetasAll.id)}
          aria-expanded={expandedId === RecetasAll.id}
        >
          <ExpandMoreIcon />
        </ExpandMore>
      </CardActions>
      <Collapse in={expandedId === RecetasAll.id} timeout="auto" unmountOnExit>
        <CardContent>
          <Typography paragraph>Preparacion:</Typography>
          <Typography paragraph>{RecetasAll.pasos}</Typography>
          <Button
            href="#contained-buttons"
            variant="contained"
            onClick={handleSearch}
          >
            Ver mas
          </Button>
        </CardContent>
      </Collapse>
    </Card>
  </React.Fragment>
);

原写法的问题分析

你之前尝试用expanded存储ID,但在判断后执行setExpanded(!expanded)——这里!expanded会把ID字符串转换成布尔值(比如非空字符串会变成false),导致状态逻辑混乱。改成直接对比ID的方式,逻辑直观且不易出错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 10:25:23