[具有道具尺寸的2D数组仅更新一维

问题描述 投票:0回答:1

我正在他的React课程中通过Flavio Copes Pixel Art应用程序进行工作,我想添加一个按钮来调整“画布”的大小。 canvas是一个二维数组,其初始化方式如下:

const [matrix, setMatrix] = useState(
Array(size)
  .fill()
  .map(() => Array(size).fill(0)));

size变量作为prop从父组件向下传递,该父组件具有一个挂钩来管理输入字段中的状态。矩阵用于通过映射每行/列来渲染“像素”组件(30px x 30px div),如下所示:

<div className={css(styles.canvas)}>
      {matrix.map((row, rowIndex) =>
        row.map((_, colIndex) => {
          return (
            <Pixel
              key={`${rowIndex}-${colIndex}`}
              background={Colors[matrix[rowIndex][colIndex]]}
              onClick={() => changeColor(rowIndex, colIndex)}
            />
          );
        })
      )}
    </div>

我能够更新画布的宽度(列数),但是我认为总像素数保持不变,并且添加/减去随后的行数不等于列数。

为什么行数与列数不同?

my repo中提供所有代码。

reactjs multidimensional-array react-hooks
1个回答
0
投票

我看不到您的仓库中列/行的变化。这个功能应该可以做到的]

const updateMatrixSize = (size) => {
  setMatrix(
    matrix.length > size
      ? matrix.slice(0, size).map(it => it.slice(0, size)))
      : [ 
         ...matrix.map(it => ([...it, ...new Array(size - matrix.length).fill(0)]),
         ...new Array(size - matrix.length).fill(0)
        ]
  )
}

PS,您的回购中有错字

props.setMsatrixState(newMatrix);
© www.soinside.com 2019 - 2024. All rights reserved.