如何在Gatsby中为可重用组件返回特定图像? [英] How Can I return a specific image in Gatsby for my reusable component?

查看:79
本文介绍了如何在Gatsby中为可重用组件返回特定图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我在React中创建了一个可重用的英雄部分,并从数据文件中检索了图像,因此更新新图像所需要做的就是更新数据文件.我正在尝试将此组件转换为Gatsby,但不确定如何用我的数据文件实现其图片插件.

So I created a reusable hero section in React and I retrieve the images from a data file, so all I need to do to update the new image is I just update my data file. I'm trying to convert this component into Gatsby, but I'm not sure how to implement their images plugin with my data file.

我的图像组件以该代码rn返回我的所有图像

My image component returns all my images with this code 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代码

Below is my React code that I'm trying to convert to use gatsby

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

My data file is just an object that links the image I want to use

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

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

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

For now, I just pass in the props on the component

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

然后在我的主页组件中,我将重用该组件,但是切换使用哪个数据文件,以便获得不同的图像

Then in my home page component, I will reuse the component, but switch which data file is used, so I get a different image

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

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

So right now, my component will display img '../../images/profile.jpg' and the second section will display the house.jpg picture because I have it hard coded in my data file, but with Gatsby, how would I replicate this same method with their image component?

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

How would I write my image component in gatsby to be able to just pass in the image component anywhere in my app and then add whichever image I want to use in the component I end up adding it to?

我只看过一些教程,该教程显示了如何向查询中添加特定图像或如何一次显示文件夹中的所有图像,但是对于通过数据文件传递图像却一无所知

I've only seen tutorials showing how to add a specific image to your query or how to display all your images in your folder at one time, but haven't seen anything about passing it through a data file

推荐答案

像这样与Gatsby的Image一起工作非常棘手.但是,我必须说,您可以根据所使用的文件系统以及数据的结构以不同的方式绕过它.

It's tricky to work like that with Gatsby's Image. However, I must say that you can bypass it in different ways depending on the filesystem used and how the data is structured.

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

Keep in mind that if you set properly the filesystem in your gatsby-config.js, you are allowing Gatsby to recognize and to find all your images in your project, making them queryable and allowing them to be used by Gatsby Image component.

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方法,则使其动态变化的局限性迫使您分别进行每个查询.

You can find much better ways than querying each image in a staticQuery filtered by the path, it's not true that is the only way to achieve it. Of course, if you are using a staticQuery approach, the limitation of making it dynamic forces you to make each query separately.

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

First of all, you need to know the difference between staticQuery and page query to understand which fits you and the limitations of them.

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

If you use a page query, you can always create an approach like the following one:

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时,这种方法更具动态性,最好一一查询.

In the example above, you are using a page query to retrieve all images from a JSON file. If you set the path in your filesystem, you will be able to retrieve them using the GraphQL fragments. This approach is the more dynamic you can afford when dealing with Gatsby Image and it's better to query one by one.

对于其他文件系统,此想法仍然相同,这只是一种可适应的方法.如果您正在使用像Contentful这样的CMS,则可以下载资产并以相同的方式动态查询它们,因为文件系统允许您这样做.

The idea remains the same for other filesystems, this is just an adaptable approach. If you are using a CMS like Contentful, you can download the assets and query them dynamically in the same way since the filesystem allows you to do it.

页面查询仅在页面组件中被允许(因此命名),因此,如果您想在React独立组件中使用它以使其可重用,则需要通过props(或reducer)传递给所需的组件,并且根据收到的道具渲染盖茨比图像.

Pages queries are only allowed in page components (hence the name) so, if you want to use it in a React standalone component to make it reusable, you will need to pass via props (or reducer) to your desired component and render the Gatsby image based on the received props.

这篇关于如何在Gatsby中为可重用组件返回特定图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆