簡體   English   中英

React konva在渲染數組時僅將x更改為1個矩形

[英]React konva applies x changing only for 1 rectangle when rendering an array

我有一個這樣的對象數組: { id, width, height, margin } 當我渲染該數組並將該信息應用於反應像這樣的konva Rect組件時:

{
      topSide.map((seat, index) => (
        <Rect
          id={seat.id}
          key={seat.id}
          fill="brown"
          stroke="white"
          width={seat.width}
          height={seat.height}
          x={topSideStartPosition + index * seat.width + seat.margin}
          y={y * linesHeight - seat.height - 2}
        />
      ))
}

所以我的問題是seat.margin僅適用於1個矩形。 通常我想為第一個矩形應用一個值,為其余矩形應用另一個值。 如果數組中的對象索引為1, seat.margin等於1;如果對象索引不等於1, seat.margin等於2。這是它的外觀: 結果圖像

我認為您可能需要計算每個座位的偏移量,並使用先前的偏移量為下一個座位計算新的偏移量。

// somewhere in the top of render function
// probably need to adjust for the first seat
let offset = 0; 

// in component:
topSide.map((seat, index) => {
    if (index === 1) {
       offset += seat.width + seat.margin
    } else {
       offset += seat.width
    }
    return <Rect
      id={seat.id}
      key={seat.id}
      fill="brown"
      stroke="white"
      width={seat.width}
      height={seat.height}
      x={offset}
      y={y * linesHeight - seat.height - 2}
    />;
});

因此,當我嘗試通過添加邊距移動矩形時,它沒有用。 因此,設置offsetX並刪除seat.margin ,在這種情況下對我有幫助。

回答我的問題:

topSide.map((seat, index) => (
        <Rect
          id={seat.id}
          key={seat.id}
          fill="brown"
          width={seat.width}
          height={seat.height}
          offsetX={-2 * index}
          x={topSideStartPosition + index * seat.width}
          y={y * linesHeight - seat.height - 2}
        />
      ))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM