【问题标题】:getImage by Gatsby Image plugin returns undefined盖茨比图像插件的getImage返回未定义
【发布时间】:2022-01-19 22:41:15
【问题描述】:

我有我想要多次查询并获取不同尺寸的英雄图像,以便我可以在不同的设备尺寸中使用它。

我的英雄形象在

src/images/hero.png

这是查询代码:

export const mobileHeroImage = graphql`
  fragment mobileHeroImage on File {
    childImageSharp {
      fluid(maxWidth: 375, maxHeight: 400) {
        ...GatsbyImageSharpFluid
      }
    }
  }
`;

export const query = graphql`
  query {
    mobileHeroImage: file(relativePath: { eq: "hero.png" }) {
      ...mobileHeroImage
    }
  }
`;

这是我在 index.js 中的组件代码:

const IndexPage = ({ data }) => {

  // First console log
  console.log(data);

  // Second console log
  console.log(getImage(data.mobileHeroImage));

第一个控制台日志记录带有图像对象的对象:

即使data 内部有mobileHeroImage 对象,第二个控制台日志也会记录未定义

多维图像将作为数组传递,如下所示:

export function MyImage({ data }) {
  const images = withArtDirection(getImage(data.mobileHeroImage), [
    // I would add more sizes here for different screen sizes
    {
      media: "(max-width: 1024px)",
      image: getImage(data.smallImage),
    },
  ])
  return <GatsbyImage image={images} />
}

【问题讨论】:

    标签: gatsby gatsby-image


    【解决方案1】:

    您正在混合来自 gatsby-image(从 Gatsby v2 向后)和 gatsby-plugin-image(从 Gatsby v3 开始)的概念。

    在很多东西中,在新版本中,它们被减少为Img (v2) 和GatsbyImage (v3)。第一个采用fluidfixed props 图像数据,就像您在片段中查询的那个(...GatsbyImageSharpFluid),而GatsbyImage 采用整个image props 数据。它们的查询方式不同。

    此外,getImage 是一个辅助函数,因此它不是强制性的,尽管它可以让您的代码更清晰。事实来自 GatsbyImage (v3),这就是它在您的代码中返回 undefined 的原因。


    查看迁移指南了解更多详情:https://www.gatsbyjs.com/docs/reference/release-notes/image-migration-guide/


    也就是说,您应该根据自己的要求选择一个或另一个版本。我建议使用新版本,因为 gatsby-image 它目前已被弃用(因此请仔细检查并删除已弃用的软件包)。

    按照GatsbyImage 方法,您的查询应如下所示:

    export const mobileHeroImage = graphql`
      fragment mobileHeroImage on File {
         childImageSharp {
           gatsbyImageData(
             width: 200
             placeholder: BLURRED
             formats: [AUTO, WEBP, AVIF]
           )
         }
      }
    `;
    
    export const query = graphql`
      query {
        mobileHeroImage: file(relativePath: { eq: "hero.png" }) {
          ...mobileHeroImage
        }
      }
    `;
    

    注意:根据需要调整查询选项和参数

    现在,您的 console.logs 应该可以工作了。

      // First console log
      console.log(data);
    
      // Second console log
      console.log(getImage(data.mobileHeroImage));
    

    正如我所说,您可以省略 getImage 辅助函数,直接使用 data

    【讨论】:

      猜你喜欢
      • 2022-08-15
      • 2021-07-30
      • 1970-01-01
      • 2021-10-06
      • 2019-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-20
      相关资源
      最近更新 更多