首页 > 解决方案 > 像亚马逊一样具有放大效果的 React 图像库

问题描述

我尝试结合react-image-galleryreact-image-magnify获得具有放大预览效果的画廊,并且根据react-image-gallery文档,我将组件传递给MyReactImageMagnify组件上的renderItem道具,ImageGallery但右侧没有放大图像。

这是带有放大功能的画廊的样子https://www.amazon.com/Samsung-MicroSD-Adapter-MB-ME128GA-AM/dp/B06XWZWYVP

这是迄今为止我所拥有的代码框https://codesandbox.io/s/goofy-lumiere-gk1y1

class MyImageGallery extends Component {
  myRenderItem() {
    return <MyReactImageMagnify {...this.props} />;
  }

  render() {
    const properties = {
      thumbnailPosition: "left",
      useBrowserFullscreen: false,
      showPlayButton: false,
      renderItem: this.myRenderItem.bind(this),
      items: [
        {
          original: "https://placeimg.com/640/480/any/1",
          thumbnail: "https://placeimg.com/250/150/any/1"
        },
        {
          original: "https://placeimg.com/640/480/any/2",
          thumbnail: "https://placeimg.com/250/150/any/2"
        },
        {
          original: "https://placeimg.com/640/480/any/3",
          thumbnail: "https://placeimg.com/250/150/any/3"
        }
      ]
    };

    return <ImageGallery {...properties} />;
  }
}

编辑:亚马逊只是为了说明“向右放大”。我制作了另一个带有 2 列网格的代码框,您可以看到普通<MyReactImageMagnify />组件的工作原理和<MyImageGallery />不工作原理。https://codesandbox.io/s/practical-browser-0dbyo

标签: reactjszoomingpreviewimage-gallery

解决方案


我认为问题在于元素溢出。图库使用overflow: hidden隐藏不可见的幻灯片,因此也隐藏了缩放的图像。

好处react-image-magnify是您可以指定要在其中呈现大图像的门户。

这是沙箱:https ://codesandbox.io/s/xenodochial-rosalind-g9ve4

创建一个带有 id 的新 div,您希望在其中显示大图像:

<Grid container spacing={4}>
  <Grid item xs={6}>
    <MyImageGallery />
  </Grid>
  <Grid container spacing={2} item xs={6} direction="column">
    <Grid item>
      <div id="myPortal" />
    </Grid>
  </Grid>
</Grid>

画廊的每个元素都将是一个 ReactImageMagnify 组件,其中门户 id 作为属性:

<ReactImageMagnify
  {...{
    smallImage: {
      alt: "Wristwatch by Ted Baker London",
      isFluidWidth: true,
      src: "https://placeimg.com/640/480/any"
    },
    largeImage: {
      src: "https://placeimg.com/640/480/any",
      width: 640,
      height: 480
    },
    enlargedImagePortalId: "myPortal"
  }}
/>

推荐阅读