如何使用图像组件向Gatsby中的页面动态添加图像? [英] How can I dynamically add images to my pages in Gatsby using the image component?

查看:100
本文介绍了如何使用图像组件向Gatsby中的页面动态添加图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我具有可渲染2张不同图像的图像组件,但是我希望能够将我的图像组件添加到任何页面,并仅将特定图像作为道具传递,而不必对新查询进行硬编码我需要使用的每个图像.

So I have the image component that renders 2 different images, but I want to be able to just add my image component to any page and just pass in the specific image as a prop instead of having to hard code a new query for each image I need to use.

如果我有50张图片,我想只将image-50.jpg作为道具传递,而不是对其进行特定查询.是否可以在gatsby中使用graphql做到这一点?

If I had 50 images, I'd like to just pass image-50.jpg in as a prop instead of making a specific query for it. Is there a way to do that with graphql in gatsby?

这是我当前的图像组件代码

Here is my current image component code

      import { graphql, useStaticQuery } from "gatsby"
      import Img from "gatsby-image"
      import React from "react"

      const Image = () => {
        const data = useStaticQuery(graphql`
          query {
            astronaut: file(relativePath: { eq: "gatsby-astronaut.png" }) {
              childImageSharp {
                fluid(maxHeight: 600) {
                  ...GatsbyImageSharpFluid
                }
              }
            }
            person: file(relativePath: { eq: "profile.jpg" }) {
              childImageSharp {
                fluid(maxHeight: 600) {
                  ...GatsbyImageSharpFluid
                }
              }
            }
          }
        `)

        return (
          <>
            <Img fluid={data.astronaut.childImageSharp.fluid} />
            <Img fluid={data.person.childImageSharp.fluid} />
          </>
        )
      }

      export default Image

有没有一种方法可以动态添加图像,然后将其渲染到新页面?

Is there a way to just add the image dynamically and then render it to a new page?

类似这样的 <Image src={"profile.jpg"} />

我不知道如何将其添加到graphql并想象我有50张图像,那么我将不得不映射全部50张图像或手动添加每个查询,这没有任何意义

I don't know how I could add that to the graphql and imagine I have 50 images, then I would have to either map through all 50 or manually add each query and that doesn't make sense

推荐答案

正如 Apena的答案所述,工作很棘手就像盖茨比的形象一样.但是,我必须说,您可以根据所使用的文件系统以及数据的结构以不同的方式绕过它.

As Apena's answer explains, 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天全站免登陆