reactjs - 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>
);
}
解决方案
你有几个选择:
- 在页面查询中查询所有图像数据,然后将数据道具钻到使用它来显示图像的组件中。
- 使用 Gatsby v3+,使用新
StaticImage
组件对每个组件的图像引用进行硬编码。 - 如果您有一个组件多次使用不同的内容/图像,但您的内容是静态父组件,您可以利用上面的选项 #2,但将图像组件作为道具或子组件向下传递。
推荐阅读
- python - 数组作为张量流的输入
- discrete-mathematics - 我如何证明这个离散数学挑战?
- c# - macos 上的 CSC 没有列出 C# 9
- c - 如何在C中为二维数组的随机元素赋值
- reactjs - React:如何将值传递给我的主 App() 函数
- javascript - 如何从数据库中添加日期的月份并在网页中显示
- c++ - 哪个是在 C++ 中存储 1 个键和 2 个值的最佳数据结构
- python - 如何检查函数是否在python中返回一种类型的数据或另一种类型的数据
- ios - iOS上的德语蓝牙键盘字符错误
- spring - ibm rad 8, was 7, spring 3.2.9 和 xerces 问题