首页 > 解决方案 > Gatsby GraphQL 组件中的变量

问题描述

我是一名 iOS 开发人员,我一直在努力争取从头开始制作我的投资组合网站的最长时间。我尝试了很多不同的技术,最终决定使用 Gatsby 来创建它。

到目前为止,事情都相当简单,但我一生都无法弄清楚如何获得如下图所示的组件。我已经完成了大部分布局设计工作,但我似乎无法使用 graphql 来查询组件中我需要的图像。

所需布局

在此处输入图像描述

我发现了很多 Gatsby 示例模板,例如这个这个相似的。然而,主要区别在于它们中的每一个都只有一个图像,并且它们似乎使用的是 Gatsby 2.0 而不是 3.0。

我可以使用“useStaticQuery”获取一个图像,但是我需要访问每个组件的不同图像。据我了解,这不可能在组件内完成,只能在页面上完成。我也不能将图像路径作为变量传递给StaticImage

export default function App(props) {
  const query = useStaticQuery(graphql`
    query AppSectionImages {
      icon: file(relativePath: { eq: "EzMaxRequest/AppIcon_180.png" }) {
        childImageSharp {
          gatsbyImageData(
            width: 200
            placeholder: BLURRED
            formats: [AUTO, WEBP, AVIF]
          )
        }
      }
    }
  `);
  const image = getImage(query.icon);
  const app = props.app;

  return (
    <div>
      <h1>{app.title}</h1>
      <GatsbyImage image={image} />
    </div>
  );

结果

在此处输入图像描述

谁能向我解释如何在组件中获得所需的布局?

编辑

这是我正在做的一些相关代码。

这是我的 index.js 主页。

export default function IndexPage({ data }) {
  const projects = data.apps.edges;
  return (
    <Layout>
      <SEO title="Home" />
      <HeroSection />
      <DescriptionSection />
      <div>
        {projects.map(({ node: project }) => (
          <AppSection app={project} />
        ))}
      </div>
      <FooterSection />
    </Layout>
  );
}

//export page query
export const query = graphql`
  query Apps {
    apps: allAppsJson(sort: { order: ASC, fields: order }) {
      edges {
        node {
          appLink
          title
          tagline
          moreLink
          order
          icon
        }
      }
    }
  }
`;

这是组件。

export default function App(props) {
  const query = useStaticQuery(graphql`
    query AppSectionImages {
      icon: file(relativePath: { eq: "EzMaxRequest/AppIcon_180.png" }) {
        childImageSharp {
          gatsbyImageData(
            width: 200
            placeholder: BLURRED
            formats: [AUTO, WEBP, AVIF]
          )
        }
      }
    }
  `);
  const image = getImage(query.icon);
  const app = props.app;

  return (
    <div>
      <h1>{app.title}</h1>
      <GatsbyImage image={image} alt={app.title} />
    </div>
  );
}

标签: reactjsgatsbygatsby-image

解决方案


你有几个选择:

  1. 在页面查询中查询所有图像数据,然后将数据道具钻到使用它来显示图像的组件中。
  2. 使用 Gatsby v3+,使用新StaticImage组件对每个组件的图像引用进行硬编码。
  3. 如果您有一个组件多次使用不同的内容/图像,但您的内容是静态父组件,您可以利用上面的选项 #2,但将图像组件作为道具或子组件向下传递。

推荐阅读