传递来自state和GraphQL的图像道具



我从"gatsby-plugin-image">

我有一个像这样创建的可重用组件:

<section className={this.props.className}> 
<div className="flexCol summaryStyles">
<h3 className="boldStyles">{this.props.title}</h3>
{this.props.copy}
</div>
<div className="imagecontainerStyles">
{this.props.image}
</div>
</section>

我想使用这个可重用的组件来显示不同的图像(在我的src/images文件夹结构中,我有一个名为"process"我将在其中放置多个图像)。{this.props内部。我想传入一个像这样的GatsbyImage组件:

{this.state.map((item, index) =>
<Process 
key={index}
className={item.className}
title={item.title}
copy={item.copy}
image={<GatsbyImage image={item.image} alt={item.alt}></GatsbyImage>}
>
</Process>
)}

我的状态设置是这样的(我现在只有一个项目,但以后会有多个项目):

constructor(props) {
super(props);
this.state = [
{
className: "flexRow flexRowL",
title: "EXPLORE",
copy: <p className="pStyles">I did <strong>user interviews</strong> with people that have food allergies to find out what their experiences have been when eating out, specifically ordering food to go.</p>,
image: this.props.data.pics.edges[0],
alt: "Explore UI image"
}
];
}

我的GraphQL设置如下:

export const pageQuery = graphql `
query {
pics: allFile(filter: {relativeDirectory: {eq: "process"}}) {
edges {
node {
name
childImageSharp {
id
}
}
}
}
}
`

我得到的唯一的东西是:网站截图预览

我不确定我做错了什么,如果有人能帮助或解释我真的很感激。我已经通读了关于盖茨比的文档和StackOverflow上的帖子,但我似乎无法理解。这是我第一次使用GraphQL。

我认为您的方法是有效的,但我认为您缺少GraphQL查询中的关键数据,以允许Gatsby打印您的图像。它应该是这样的:

export const pageQuery = graphql `
query {
pics: allFile(filter: {relativeDirectory: {eq: "process"}}) {
edges {
node {
name
childImageSharp {
gatsbyImageData(
width: 200
placeholder: BLURRED
formats: [AUTO, WEBP, AVIF]
)
}
}
}
}
}
`

注意:当然,调整和自定义占位符(或删除它,如果你想)

您需要从图像中获取gatsbyImageData,以便将其用作GatsbyImage组件中的image属性。

在此之后,您的数据应该始终是gatsbyImageData,因此:

image: this.props.data.pics.edges[0],

应该成为:

image: this.props.data.pics.edges.node[0].childImageSharp.gatsbyImageData,

数组是node,而不是edges,所以取第一个元素(目前)应该在node[0]。在那里,正如我所说,需要的数据是gatsbyImageData,所以你需要继续嵌套,直到你到达它。

最新更新