1

试图从 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>
4

1 回答 1

2

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

因为你images在你的定义gatsby-config.js,我建议过滤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;
  // ...
于 2020-02-09T21:59:53.760 回答