问题描述
我是一名 iOS 开发人员,我一直在努力从头开始制作我的作品集网站,这似乎是最长的时间。我尝试了很多不同的技术,最终决定使用 Gatsby 来创建它。
到目前为止,事情相当简单,但我一生都无法弄清楚如何获得如下图所示的组件。我已经完成了大部分布局设计,但我似乎无法使用 graphql 来查询组件中我需要的图像。
所需的布局
我发现了很多类似的 Gatsby 示例模板,例如这个 one 和这个 one。然而,主要区别在于,它们中的每一个都只有一个图像,而且它们似乎使用 Gatsby 2.0 而不是 3.0。
我可以使用“useStaticQuery”获取一张图像,但是我需要访问每个组件的不同图像。根据我的理解,这不可能在组件内完成,只能在页面上完成。我也无法将图像路径作为变量传递给 StaticImage。
onClick
结果
谁能向我解释如何在组件中获得所需的布局?
编辑
这是我正在做的一些相关代码。
这是我的 index.js 主页。
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>
);
这是组件。
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
}
}
}
}
`;
解决方法
您有几个选择:
- 在页面查询中查询所有图像数据,并将数据推进到使用它来显示图像的组件。
- 使用 Gatsby v3+,使用 the new
StaticImage
component 对每个组件的图像引用进行硬编码。 - 如果您有一个组件多次使用不同的内容/图片,但有一个静态父组件包含您的内容,您可以利用上面的选项 #2,但将图片组件作为道具或子组件向下传递。