gatsby-starter-default starter中Image组件的作用是什么?

mmm*_*mmm 5 gatsby

我不知道 components 文件夹中的 image.js 文件是否应该接受参数,指定诸如流体与固定、图像大小、应该渲染哪个图像等,然后根据参数渲染任何图像。

如果不是,那么标准使用 image.js 是不是为要显示的每个图像基于 image.js 制作一个新文件?如果是这样,这样做有什么好处?

我阅读了有关 image.js 的内容,但我仍然不明白这个问题。

image.js 组件:https : //github.com/gatsbyjs/gatsby-starter-default/blob/master/src/components/image.js

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

/*
 * This component is built using `gatsby-image` to automatically serve optimized
 * images with lazy loading and reduced file sizes. The image is loaded using a
 * `StaticQuery`, which allows us to load the image from directly within this
 * component, rather than having to pass the image data down from pages.
 *
 * For more information, see the docs:
 * - `gatsby-image`: https://gatsby.dev/gatsby-image
 * - `StaticQuery`: https://gatsby.dev/staticquery
 */

const Image = () => (
  <StaticQuery
    query={graphql`
      query {
        placeholderImage: file(relativePath: { eq: "gatsby-astronaut.png" }) {
          childImageSharp {
            fluid(maxWidth: 300) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    `}
    render={data => <Img fluid={data.placeholderImage.childImageSharp.fluid} />}
  />
)
export default Image
Run Code Online (Sandbox Code Playgroud)

Chr*_*ams 2

这里发生了一些事情。

首先,这只是具有静态查询的组件的示例。它仅显示了一个示例 graphql 查询来提取图像并渲染图像数据。您可能会从父组件中调用它。

您可以为每个图像创建这样的组件,但您不必这样做。

使用上面的示例,您无法传入参数。我最近尝试过,但 graphql 插值字符串不允许传入参数,但对于此示例,有一个解决方法,如Wes Bos 发布的链接所示。简而言之,解决方法是使用 graphql 查询返回每个图像,然后使用诸如 map 之类的东西来梳理出感兴趣的图像。使用此解决方法,我成功地在您的帖子中创建了示例的通用版本,其中我传递了感兴趣的图像的名称。不过,如果您的网站中有数百张图像,显然这并不理想。

您可以将参数传递到“页面组件”的 graphql 查询中。Gatbsy 教程(https://www.gatsbyjs.org/tutorial/)非常出色,我无法强调完成整个教程是多么值得。第四部分和第五部分讨论 graphql 以及查询和图像的使用。

使用图像时,建议的方法是使用示例中使用的gatsby-image ( https://www.gatsbyjs.org/packages/gatsby-image/ )。

我还创建了另一个通用图像组件,它接受图像数据,而不是图像名称作为道具。在父页面组件中,我可以定义一个常量 graphql 查询,然后将其结果传递到我的图像组件中。这种方法可以扩展到作为图像库的页面组件。例如,查询可以返回文件夹中的所有图像或匹配正则表达式。可以迭代查询请求,通过传入图像数据来为每个图像创建图像组件。

我故意不包含代码示例,因为链接包含我上面描述的所有示例。