首页 > 解决方案 > 如何使用引导网格映射图像数组?

问题描述

我正在用 gatsby.js 构建一个投资组合网站。所有照片都发布在 wordpress 中,由 graphQL 获取并呈现到网站上。

我正在尝试使用引导网格来组织照片并使其具有响应性,但是因为 graphQL 返回一个包含从 wordpress 帖子中获取的所有图像的数组,所以我无法使用 class='row' 设置一个 div,因为我正在使用数组。地图。而且我不知道如何解决。

从graphQL我将分辨率设置为宽度= 300像素和高度= 300像素。

这是我发现组织尺寸的唯一方法,只要我不能使用类行并且所有图像都被视为一行。问题是照片尺寸没有反应,所以总是300X300...

我想要一种让它成为网格系统的方法,因为它应该可以工作......所以当我调整窗口大小时,所有照片都会被组织和调整大小。


const IndexPage = () => {
    const data = useStaticQuery(graphql`
        query {
            allWordpressPost {
                edges {
                    node {
                        title
                        featured_media {
                            localFile {
                                childImageSharp {
                                    resolutions(width: 300, height: 300) {
                                        src
                                        width
                                        height
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    `);
    const imagesResolutions = data.allWordpressPost.edges.map(
        (edge) => edge.node.featured_media.localFile.childImageSharp.resolutions
    );
    return (
        <Layout>
            <Jumbotron />
            <div className="container">
                <h1 className="my-5 text-center">Portfolio</h1>
                {imagesResolutions.map((imageRes) => (
                    <Img className="col-sm-6 col-lg-4 img-rounded img" resolutions={imageRes} key={imageRes.src} />
                ))}
            </div>
        </Layout>
    );
};

标签: wordpressreactjsbootstrap-4graphqlgatsby

解决方案


如果您将data.allWordpressPost.edges数组拆分为一个分块数组,您可以循环遍历外部数组以进行渲染rows,并通过每个内部数组进行渲染cols

对于 3 列自举网格,您希望传入 3 的大小值(它是lodash.chunk本示例中的第二个参数)。这确保了每个块的长度为 3。

这是一个简单的例子,忽略了 graphql、childImageSharp 和 gatsby-image 的使用。

import ReactDOM from 'react-dom';
import React, { Component } from 'react';
import arrayChunk from 'lodash.chunk';
import 'bootstrap/dist/css/bootstrap.min.css';

const IndexPage = () => {

  const rawData = [1, 2, 3, 4, 5, 6];
  const chunkedData = arrayChunk(rawData, 3)

  return (
    <div>
      <div className="container">
        {chunkedData.map((row, rowIndex) => {
          return (<div key={rowIndex} className="row">{
            row.map((col, colIndex) => {return (<div key={colIndex} className="col-sm">{col}</div>)})
          }</div>)
        }
        )}
      </div>
    </div>
  );
};

ReactDOM.render(<IndexPage />, document.getElementById('root'));

堆栈闪电战


推荐阅读