如何在二维循环中为 div 创建 Ref

How to create Ref for a div in two dimensional loop

我在这里尝试将 ref 属性传递给 div 但它没有发生,任何人都可以帮助我解决这个问题


 const ref = useRef<HTMLDivElement>(null);

 for (let curRow = 1; curRow <= props.row; curRow++) {
    for (let curCol = 1; curCol <= props.col; curCol++) {
      columns.push(
        <div
          ref={ref}
          style={{ minWidth: `${minWidth}px` }}
          className="el1"
          id={`${curRow}${curCol}}`}
          key={`${curRow}${curCol}${generateKey(curCol)}`}
        >{`${curRow}${curCol}`}</div>
      );
    }
  }```

如果你想要对所有 div 的引用,那么你不能使用单个引用,你需要它们的数组,或者它们的二维数组。例如:

const refs = useRef<(HTMLDivElement | null)[][]>([]);

for (let curRow = 0; curRow < props.row; curRow++) {
  for (let curCol = 0; curCol < props.col; curCol++) {
    columns.push(
      <div
        ref={(el) => {
          refs.current[currRow] = refs.current[currRow] || [];
          refs.current[currRow][currCol] = el;
        }}
        style={{ minWidth: `${minWidth}px` }}
        className="el1"
        id={`${curRow}${curCol}}`}
        key={`${curRow}${curCol}${generateKey(curCol)}`}
      >{`${curRow}${curCol}`}</div>
    );
  }
}

// used like:
useEffect(() => {
  console.log("Element at zero/zero: ", refs.current[0][0]);
}, []);