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

嵌套Map函数致时间线堆叠条形图显示异常求助

嵌套数据下时间线水平条形图堆叠显示异常问题解决

问题背景

我被嵌套Map的使用困扰多日,想要在时间线中绘制带起止日期的水平条形图。所有条形图需要堆叠显示,非嵌套数据时功能正常,但改用嵌套数据对象后,所有条形图都渲染在同一行,无法依次排列。

嵌套数据格式

const bars = [
  {
    title: "June 24",
    bookings: [
      {
        Beginn_Datum: "2024-06-05T22:00:00.000Z",
        Ende_Datum: "2024-06-08T22:00:00.000Z",
      },
      {
        Beginn_Datum: "2024-06-05T22:00:00.000Z",
        Ende_Datum: "2024-06-08T22:00:00.000Z",
      },
    ],
  },
];

问题分析

  1. CSS布局冲突:原代码中.bar-chart和.bar-wrapper都设置了固定高度300px,导致每个wrapper占满整个容器高度,内部条形图自然重叠在同一垂直空间。
  2. 索引重复:Bar组件的index使用外层category的索引,同一category下的多个bookings会共享同一个index值,导致它们被渲染到同一垂直位置。

解决方案

1. 修正索引计算

给每个booking分配唯一的全局索引,确保Bar组件能获得不同的垂直位置参数:

<div className="bar-chart">
  {bars.flatMap((category, catIndex) => 
    category.bookings.map((bar, bookIndex) => {
      // 计算全局唯一索引,保证每个Bar的垂直位置不重复
      const globalIndex = catIndex * category.bookings.length + bookIndex;
      const { startPosition, width } = calculatePercentage(
        new Date(bar.Beginn_Datum),
        new Date(bar.Ende_Datum),
        minDate,
        maxDate,
        scale
      );
      return (
        <Bar
          key={`${catIndex}-${bookIndex}`}
          startPosition={startPosition}
          width={width}
          index={globalIndex}
          label={bar.Beginn_Datum}
        />
      );
    })
  )}
</div>

2. 调整CSS布局

去掉容器的固定高度,给单个条形图容器设置合适高度,确保垂直堆叠:

.bar-chart {
  position: relative;
  height: auto; /* 由内容撑开高度 */
  display: flex;
  flex-direction: column;
  gap: 8px; /* 可选:条形图之间添加间距 */
  z-index: 2;
}

.bar-wrapper {
  position: relative;
  height: 40px; /* 设置单个条形图的高度 */
}

3. 检查Bar组件样式

确保Bar组件根据index属性正确计算垂直位置,比如:

.bar {
  position: absolute;
  height: 100%;
  top: 0;
  /* 若使用index计算偏移,示例:top: ${props.index * 40}px; */
  background-color: #2196F3;
  border-radius: 4px;
}

这样修改后,所有条形图会按照预期垂直堆叠显示,每个booking对应独立的一行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 04:45:20