首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用gatsby-image映射图像

使用gatsby-image映射图像
EN

Stack Overflow用户
提问于 2020-02-10 01:05:35
回答 1查看 692关注 0票数 1

尝试映射gatsby项目中文件夹中的图像。我根据我所看到的指南设置了一个我认为可以工作的查询。我没有得到任何错误和网站加载,但图像不显示。有什么想法吗?谢谢!

gatsby-config.js:

代码语言:javascript
复制
  plugins: [
    `gatsby-plugin-react-helmet`,
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },

查询:

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

    `)

返回:

代码语言:javascript
复制
            <div className='socialPhotos'>
                {data.allFile.edges.map(node => 
                    <Img 
                      key={node.id}
                      title="Photo image"
                      alt="Photo"
                      fixed={node.childImageSharp.fixed}
                    />
                    )}
            </div>
EN

回答 1

Stack Overflow用户

发布于 2020-02-10 05:59:54

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

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

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

将您的查询粘贴到浏览器中的GraphiQL中,并测试是否获得数据:http://localhost:8000/___graphql

编辑

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

代码语言:javascript
复制
const YourComponent = (props) => {
  const { data: { allFile: { edges } } } = props;
  const oneImage = edges.filter(
    el => el.node.childImageSharp.fixed.originalName === "yourImageFileName.png")
    [0].node.childImageSharp.fixed;
  // ...
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60139088

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档