【问题标题】:Dynamic images from array来自阵列的动态图像
【发布时间】:2021-10-05 14:01:21
【问题描述】:

在 Gatsby 中,如果路径是动态的,如何显示图像?

我有一个这样的数组:

const pics = [
    {
        title: "doggo",
        src: "../images/dog.png",
    },
    {
        title: "kitty",
        src: "../images/cat.png",
    },
];

我知道我不能使用 StaticImage 组件,所以我认为我需要使用 GastbyImage 组件,通过 GraphQL 查询获取我的图像。但是怎么做呢?

PS:我使用默认安装程序附带的“gatsby-plugin-image”。

【问题讨论】:

    标签: gatsby


    【解决方案1】:

    首先,您需要允许 Gatsby 通过设置文件系统从这些图像创建可查询节点:

    const path = require(`path`)
    
    module.exports = {
      plugins: [
        {
          resolve: `gatsby-source-filesystem`,
          options: {
            name: `images`,
            path: path.join(__dirname, `src`, `images`),
          },
        },
        `gatsby-plugin-image`,
        `gatsby-plugin-sharp`,
        `gatsby-transformer-sharp`,
      ],
    }
    

    在构建时,Gatsby 将识别 /src/images 文件夹,并在使用变换器和锐器处理您的图像后创建 GraphQL 节点。

    您将公开一些有关文件系统配置的有用过滤器和节点,在 localhost:8000/___graphql 中对其进行测试,但它们应该如下所示:

    {
      allFile(filter: { sourceInstanceName: { eq: "images" } }) {
        edges {
          node {
           childImageSharp {
              gatsbyImageData(
                width: 200
                placeholder: BLURRED
                formats: [AUTO, WEBP, AVIF]
              )
            }
          }
        }
      }
    }
    

    sourceInstanceName images 代表gatsby-source-filesystem 中的name 属性。

    您的图像数据由props.data.allFile.node 保存,因此您可以在任何页面中:

    import { graphql } from "gatsby"
    import { GatsbyImage, getImage } from "gatsby-plugin-image"
    
    function YourPage({ data }) {
    
     return (
       <section>
       {data.allFile.edges.map(({ node }) => <GatsbyImage image={node.childImageSharp.gatsbyImageData})} alt={node.title} key={node.title}/>
       </section>
     )
    }
    
    export const pageQuery = graphql`
     query {
       allFile(filter: { sourceInstanceName: { eq: "images" } }) {
         edges {
           node {
            title
            childImageSharp {
               gatsbyImageData(
                 width: 200
                 placeholder: BLURRED
                 formats: [AUTO, WEBP, AVIF]
               )
             }
           }
         }
       }
     }
    `
    

    根据您的要求或规范对其进行调整。

    【讨论】:

      猜你喜欢
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多