在React网格中获取图片高度

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

我正在React中制作砖石网格图库,在加载后和使用网格调整大小之前,我都无法获得图像高度。我有 onLoad 处理人 img 但在那里我得到的只是已经调整过的图片高度,而它应该是原始的,用它来计算行跨度的数量。我知道这可能是纯粹的css问题,但我不知道如何解决。

下面是我的 useEffect:

  useEffect(() => {
    if (imageRef.current && !loading) {
      const height = imageRef.current.clientHeight;
      console.log('height', height);
      const spansCount = Math.ceil(height / 10 + 1);
      setSpansCount(spansCount);
    }
  }, [imageRef.current, loading]);

这是我的 render:

 return (
    <div
      {...rest}
      className={styles.gallery__item}
      style={{ gridRowEnd: `span ${spansCount}` }}
    >
      <img
        src={image.previewURL}
        ref={imageRef}
        className={styles.gallery__img}
        alt={image.tags}
        onLoad={handleLoad}
      />
      <Placeholder
        ref={loaderRef}
        style={loading ? { display: 'block' } : { display: 'none' }}
      />
    </div>

这是我的非工作 代码和盒子.

而这里是 工作 代码和盒子react-load-image 包,但我不知道为什么这个能用,而第一个不能用。

css reactjs grid
1个回答
0
投票

我只需要改变图像上的css。

.gallery__img {
  width: 100%;
  height: auto; // not 100%
}
© www.soinside.com 2019 - 2024. All rights reserved.