【问题标题】:How to create Ref for a div in two dimensional loop如何在二维循环中为 div 创建 Ref
【发布时间】:2022-01-02 13:04:07
【问题描述】:

在这里我试图将 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>
      );
    }
  }```

【问题讨论】:

  • 您是否想让 ref 指向 all 的 div?还是有你想要的特定 div?
  • 我想引用所有的 div

标签: reactjs react-hooks ref


【解决方案1】:

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

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]);
}, []);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-08
    • 2018-03-31
    相关资源
    最近更新 更多