简体   繁体   English

Gatsby graphql 查询 GatsbyImage 以使用项目中的本地图像

[英]Gatsby graphql query for GatsbyImage to use a local image from project

I'd just like to use an image using GatsbyImage component.我只想使用 GatsbyImage 组件的图像。

Normally you do it using <img src='./img.jpg'/> .通常你使用<img src='./img.jpg'/> How is it done with GatsbyImage , so i can send an image using props. GatsbyImage是如何完成的,所以我可以使用道具发送图像。

If you want to use GatsbyImage you need to provide extra GraphQL node data that Gatsby infers using its transformers and sharps.如果你想使用GatsbyImage ,你需要提供额外的 GraphQL 节点数据,Gatsby 使用它的转换器和锐器推断。 To do so, you need to tell Gatsby where those images are, in your case, by setting the following snippet in the gatsby-config.js :为此,您需要通过在gatsby-config.js中设置以下代码段来告诉 Gatsby 这些图像在哪里:

{
  resolve: `gatsby-source-filesystem`,
  options: {
    name: `componentImages`,
    path: `${__dirname}/src/components`,
  },
},

Note: you can have many instances of the gatsby-source-filesystem注意:您可以拥有多个gatsby-source-filesystem实例

After starting the gatsby develop again to refresh the sources, you will see the node available in the GrahiQL playground (localhost:8000/___graphql) where you should test your query but it should look like:再次启动gatsby develop以刷新源代码后,您将在 GrahiQL 游乐场 (localhost:8000/___graphql) 中看到可用的节点,您应该在其中测试您的查询,但它应该如下所示:

  image: file(relativePath: {eq: "free-time.jpg"}) {
    childImageSharp {
      gatsbyImageData
    }
  }

After npm init gatsby , 'src/images' folder is created and this is the basic root of the relative path which is set by default in gatsby.config.jsnpm init gatsby之后,会创建'src/images'文件夹,这是gatsby.config.js中默认设置的相对路径的基本根目录

{
         resolve: 'gatsby-source-filesystem',
         options: {
            name: 'images',
            path: `./src/images/`,
         }
}

So put your img.jpg to images folder and query by using relative path因此,将您的 img.jpg 放入 images 文件夹并使用相对路径进行查询

   const data = useStaticQuery(graphql`
  {
     file(relativePath: { eq: "free-time.jpg" }) {
        childImageSharp {
           gatsbyImageData
        }
     }
  }
`);

and insert it to GatsbyImage并将其插入 GatsbyImage

 const img = getImage(data.file);

 <GatsbyImage image={img} />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM