【问题标题】:mapping images with gatsby-image用 gatsby-image 映射图像
【发布时间】:2020-02-09 17:05:34
【问题描述】:

尝试从 gatsby 项目中的文件夹映射图像。我以我认为可以根据我看过的指南工作的方式设置查询。我没有收到任何错误并且网站加载,但图像没有显示。有什么想法吗?谢谢!

gatsby-config.js:

  plugins: [
    `gatsby-plugin-react-helmet`,
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },

查询:

    const data = useStaticQuery(graphql`
      query {
        allFile(filter:{extension:{regex:"/social/"}}) {
          edges {
            node {
              childImageSharp {
                fixed(width: 150, height: 150) {
                    ...GatsbyImageSharpFixed
                }
              }
            }
          }
        }
      }

    `)

返回:

            <div className='socialPhotos'>
                {data.allFile.edges.map(node => 
                    <Img 
                      key={node.id}
                      title="Photo image"
                      alt="Photo"
                      fixed={node.childImageSharp.fixed}
                    />
                    )}
            </div>

【问题讨论】:

  • 这个问题你解决了吗?

标签: javascript reactjs gatsby gatsby-image


【解决方案1】:

您的 graphQL 查询中的过滤器可能是问题所在。您是否尝试在浏览器中使用 graphiQL 进行查询?

因为您在gatsby-config.js 中定义了images,我建议使用sourceInstanceName 进行过滤:

    const data = useStaticQuery(graphql`
      query {
      allFile(filter: {sourceInstanceName: {eq: "images"}}) {
          edges {
            node {
              childImageSharp {
                fixed(width: 150, height: 150) {
                    ...GatsbyImageSharpFixed
                }
              }
            }
          }
        }
      }
    `)

将您的查询粘贴到浏览器中的 GraphiQL 中,然后测试您是否能取回数据:http://localhost:8000/___graphql

编辑

这就是您如何从组件内的查询中获取一张图片

const YourComponent = (props) => {
  const { data: { allFile: { edges } } } = props;
  const oneImage = edges.filter(
    el => el.node.childImageSharp.fixed.originalName === "yourImageFileName.png")
    [0].node.childImageSharp.fixed;
  // ...

【讨论】:

  • 我尝试了该查询,但我收到了一条错误“TypeError: Cannot read property 'fixed' of undefined”这行:fixed={node.childImageSharp.fixed} 在 GraphiQL 中,它给了我一堆未知片段。这就是我从其他有效的 gatsby-image 查询中得到的结果。所以也许是一件好事的开始?
  • 抱歉,我应该解释一下我正在映射图像以将它们全部显示在网格中。
猜你喜欢
  • 2021-03-18
  • 2021-07-17
  • 1970-01-01
  • 2020-07-13
  • 2021-03-27
  • 1970-01-01
  • 2021-03-29
  • 2020-05-25
  • 2020-05-10
相关资源
最近更新 更多