【问题标题】:how can i map my default export in GraphQL with Gatbsy Image?如何使用 Gatsby Image 映射我在 GraphQL 中的默认导出?
【发布时间】:2020-05-25 07:49:49
【问题描述】:

我想在 GraphQL 中映射我的导出,而不是重复我的图像 3 次,检查我的代码以了解我。

这是我的出口:

    export default [
  {
    id: Math.random(),
    imageUrl: require("../../images/recent-game/1.jpg"),

  },
  {
    id: Math.random(),
    imageUrl: require("../../images/recent-game/2.jpg"),

  },
  {
    id: Math.random(),
    imageUrl: require("../../images/recent-game/3.jpg"),

  },
]

这是我的导入和 GraphQL

import BackgroundImage from "gatsby-background-image"
import { useStaticQuery, graphql } from "gatsby"
const getData = graphql`
  {
    image1: file(relativePath: { eq: "recent-game/1.jpg" }) {
      childImageSharp {
        fluid {
          ...GatsbyImageSharpFluid
        }
      }
    }
    image2: file(relativePath: { eq: "recent-game/2.jpg" }) {
      childImageSharp {
        fluid {
          ...GatsbyImageSharpFluid
        }
      }
    }
    image3: file(relativePath: { eq: "recent-game/3.jpg" }) {
      childImageSharp {
        fluid {
          ...GatsbyImageSharpFluid
        }
      }
    }

  }
`

在这里我想映射我的图像而不是重复它们,这取决于我的导出

【问题讨论】:

    标签: reactjs graphql gatsby graphql-js gatsby-image


    【解决方案1】:

    一个可重用的图像组件怎么样?

    // Image
    import React from 'react';
    import { StaticQuery, graphql } from 'gatsby';
    import Img from 'gatsby-image';
    
    const Image = props => (
      <StaticQuery
        query={graphql`
          query {
            images: allFile {
              edges {
                node {
                  relativePath
                  name
                  childImageSharp {
                    fluid(maxWidth: 1000) {
                      ...GatsbyImageSharpFluid
                    }
                  }
                }
              }
            }
          }
        `}
        render={data => {
          const image = data.images.edges.find(n => {
            return n.node.relativePath.includes(props.filename);
          });
          if (!image) {
            return null;
          }
    
          // const imageSizes = image.node.childImageSharp.sizes; sizes={imageSizes}
          return <Img alt={props.alt} fluid={image.node.childImageSharp.fluid} />;
        }}
      />
    );
    
    export default Image;
    

    还有地图组件。

    // Parent
    {
      [
        { id: 0, filename: "gatsby-icon.png" },
        { id: 1, filename: "gatsby-icon.png" }
      ].map(item => {
        return (
          <div key={item.id}>
            <Image filename={item.filename} alt={String(item.id)} />
          </div>
        );
      });
    }
    

    你当然应该检查 gatsby-source-filesystem。

    【讨论】:

    • 我会试试你的解决方案..我希望它可以和我一起工作..谢谢
    • 不客气~。如果效果好,请选择它作为答案。 @AdamKif
    猜你喜欢
    • 1970-01-01
    • 2021-03-18
    • 2020-01-16
    • 2021-03-29
    • 2021-06-20
    • 2020-06-11
    • 2021-09-15
    • 1970-01-01
    • 2020-03-09
    相关资源
    最近更新 更多