如何在Gatsby中返回可重复使用组件的特定图像



所以我在React中创建了一个可重用的英雄部分,并从数据文件中检索图像,所以我只需要更新我的数据文件就可以更新新图像。我正试图将这个组件转换为Gatsby,但我不确定如何用我的数据文件实现他们的图像插件。

我的图像组件用这个代码rn 返回我的所有图像

const Image = () => {
const data = useStaticQuery(graphql`
query {
allImageSharp {
edges {
node {
id
fluid(maxWidth: 200, maxHeight: 200) {
...GatsbyImageSharpFluid
}
}
}
}
}
`)
return (
<>
{data.allImageSharp.edges.map(edge => (
<Img fluid={edge.node.fluid} />
))}
</>
)
}

下面是我的React代码,我正试图将其转换为使用gatsby

我的数据文件只是一个链接我想使用的图像的对象

export const heroSectionOne = {
img: require('../../images/profile.jpg'),
alt: 'Image',
start: 'true'
};
export const heroSectionTwo = {
img: require('../../images/house.jpg'),
alt: 'Image',
start: 'true'
};

现在,我只是在组件上传递道具

<ImgWrapper start={start}>
<Img src={img} alt={alt} />
</ImgWrapper>

然后在我的主页组件中,我将重用该组件,但切换使用哪个数据文件,这样我就得到了一个不同的图像

<InfoSection {...heroSectionOne} />
<InfoSection {...heroSectionTwo} />

现在,我的组件将显示img'../../images/profile.jpg',第二部分将显示house.jpg图片,因为我在数据文件中对其进行了硬编码,但对于Gatsby,我如何用他们的图像组件复制同样的方法?

我该如何在gatsby中编写我的图像组件,以便能够将图像组件传递到我的应用程序中的任何位置,然后在我最终添加到的组件中添加我想使用的任何图像?

我只看过一些教程,展示了如何将特定图像添加到查询中,或者如何一次在文件夹中显示所有图像,但还没有看到任何关于通过数据文件传递图像的内容

像这样处理盖茨比的图像很棘手。但是,我必须指出,根据使用的文件系统和数据的结构,您可以以不同的方式绕过它。

请记住,如果您在gatsby-config.js中正确设置了文件系统,您将允许Gatsby识别并查找项目中的所有图像,使其可查询,并允许GatsbyImage组件使用它们。

const path = require(`path`)
module.exports = {
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: path.join(__dirname, `src`, `images`),
},
},
`gatsby-plugin-sharp`,
`gatsby-transformer-sharp`,
],
}

你可以找到比查询按路径过滤的staticQuery中的每个图像更好的方法,但这并不是实现它的唯一方法。当然,如果你使用staticQuery方法,使其动态化的限制迫使你分别进行每个查询。

首先,您需要了解staticQuery和页面查询之间的区别,以了解哪种查询适合您以及它们的局限性。

如果你使用一个页面查询,你总是可以创建一个像下面这样的方法:

import React from 'react'
import { graphql } from 'gatsby'
import Layout from '../components/layout'
class ProductPage extends React.Component {
render() {
const products = get(this, 'props.data.allDataJson.edges')
return (
<Layout>
{products.map(({ node }) => {
return (
<div key={node.name}>
<p>{node.name}</p>
<Img fluid={node.image.childImageSharp.fluid} />
</div>
)
})}
</Layout>
)
}
}
export default ProductPage

export const productsQuery = graphql`
query {
allDataJson {
edges {
node {
slug
name
image{
publicURL
childImageSharp{
fluid {
...GatsbyImageSharpFluid
}
}
}
}
}
}
}
`

在上面的示例中,您使用页面查询从JSON文件中检索所有图像。如果您在文件系统中设置了路径,您将能够使用GraphQL片段来检索它们。在处理Gatsby Image时,这种方法更具动态性,最好逐个查询。

对于其他文件系统,这个想法保持不变,这只是一种适应性强的方法。如果您使用像Contentful这样的CMS,您可以下载资产并以相同的方式动态查询它们,因为文件系统允许您这样做

页面查询只允许在页面组件中进行(因此得名(,因此,如果您想在React独立组件中使用它以使其可重复使用,则需要通过props(或reducer(传递到您想要的组件,并根据收到的props渲染Gatsby图像。

最新更新