首页 > 解决方案 > 我想使用反应以 3*X 的网格方式显示图像

问题描述

我有一个包含图像 url 的数组列表。我想使用 react-bootstrap 将每个项目绑定到一个 div 中(库不是约束,但它应该与反应兼容)。我想以一种方式对齐 div,在每一行中我只有 3 个图像,如果集合中有第 4 个项目,那么它会滑动到下一行。

下面是合集

const images = [
    {
      src:
        'https://images.unsplash.com/photo-1509420316987-d27b02f81864?dpr=1&auto=format&fit=crop&w=1500&q=80&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D',
      width: 1500,
      height: 1000,
    },
    {
      src:
        'https://images.unsplash.com/photo-1509641498745-13c26fd1ed89?dpr=1&auto=format&fit=crop&w=1000&q=80&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D',
      width: 666,
      height: 1000,
    },
    {
      src:
        'https://images.unsplash.com/photo-1491146179969-d674118945ff?dpr=1&auto=format&fit=crop&w=1500&q=80&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D',
      width: 1500,
      height: 844,
    },
{
      src:
        'https://images.unsplash.com/photo-1509420316987-d27b02f81864?dpr=1&auto=format&fit=crop&w=1500&q=80&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D',
      width: 1500,
      height: 1000,
    },
    {
      src:
        'https://images.unsplash.com/photo-1509641498745-13c26fd1ed89?dpr=1&auto=format&fit=crop&w=1000&q=80&cs=tinysrgb&ixid=dW5zcGxhc2guY29tOzs7Ozs%3D',
      width: 666,
      height: 1000,
    }
  ]
 

标签: javascripthtmlreactjsuser-interface

解决方案


我会用 display: flex 制作一个包装 Div。

<div id="img-wrapper">
 <div><img src="your image" /></div>
 <div><img src="your image" /></div>
</div>

CSS:

#img-wrapper {
 display: flex;
 flex-wrap: wrap;
}

#img-wrapper > div {
 flex: 0 1 33%;
}

flex: 告诉 child-div 它是否应该增长、缩小以及它应该具有的大小:

flex: "flex-grow" "flex-shrink" "flex-basis";

编辑:正如 Baruch Mashasha 所说,网格会更好。


推荐阅读