首页 > 解决方案 > 如何在 Gatsby 中为我的可重用组件返回特定图像?

问题描述

因此,我在 React 中创建了一个可重用的 hero 部分,并从数据文件中检索图像,因此更新新图像所需要做的就是更新我的数据文件。我正在尝试将此组件转换为 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} />
              ))}
            </>
          )
        }

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

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

 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 中编写我的图像组件,以便能够在我的应用程序中的任何位置传递图像组件,然后添加我想要在最终添加到的组件中使用的任何图像?

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

标签: reactjsgatsbygatsby-imagegatsby-plugin

解决方案


像 Gatsby's Image 这样工作是很棘手的。但是,我必须说,您可以根据使用的文件系统和数据的结构以不同的方式绕过它。

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

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方法,使其动态化的限制会迫使您分别进行每个查询。

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

如果您使用页面查询,则始终可以创建如下方法:

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 独立组件中使用它以使其可重用,您需要通过道具(或减速器)传递给您想要的组件并渲染 Gatsby图像基于收到的道具。


推荐阅读