gpt4 book ai didi

reactjs - 如何使用 gatsby-image 查询多个图像?

转载 作者:行者123 更新时间:2023-12-03 13:22:30 24 4
gpt4 key购买 nike

我有 16 张图像想要以网格格式渲染到网站上。

我为此使用以下插件:

  • gatsby-image
  • gatsby-source-filesystem
  • gatsby-plugin-sharp
  • gatsby-transformer-sharp

我阅读了文档,据我所知,它只演示了如何查询一张图像。

例如

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

export default ({ data }) => (
<div>
<h1>Hello gatsby-image</h1>
<Img fixed={data.file.childImageSharp.fixed} />
</div>
)

export const query = graphql`
query {
file(relativePath: { eq: "blog/avatars/kyle-mathews.jpeg" }) {
childImageSharp {
# Specify the image processing specifications right in the query.
# Makes it trivial to update as your page's design changes.
fixed(width: 125, height: 125) {
...GatsbyImageSharpFixed
}
}
}
}
`

但是如果我有 16 张图像,我该如何处理呢?编写 16 个单独的查询看起来相当麻烦,并且将来很难阅读。

我在引用多个图像的文档中看到了这段代码,但我在尝试访问图像本身时遇到了麻烦。

例如

export const squareImage = graphql`
fragment squareImage on File {
childImageSharp {
fluid(maxWidth: 200, maxHeight: 200) {
...GatsbyImageSharpFluid
}
}
}
`

export const query = graphql`
query {
image1: file(relativePath: { eq: "images/image1.jpg" }) {
...squareImage
}

image2: file(relativePath: { eq: "images/image2.jpg" }) {
...squareImage
}

image3: file(relativePath: { eq: "images/image3.jpg" }) {
...squareImage
}
}
`

我的文件夹结构如下:

---package.json

---源代码

------图片

---------16张图片

------页面

---------我要在其中渲染 16 张图像的页面

等等

谢谢。

最佳答案

研究一下 GraphiQL 应该会对您有所帮助,尤其是 Explorer。但请记住,Gatsby 片段在 GraphiQL 中不起作用。

{
allImageSharp {
edges {
node {
id
fluid(maxWidth: 200, maxHeight: 200) {
...GatsbyImageSharpFluid
}
}
}
}
}

所以上面的内容应该等于下面的查询,在 GraphiQL 中工作

{
allImageSharp {
edges {
node {
id
fluid(maxHeight: 200, maxWidth: 200) {
src
srcSet
base64
aspectRatio
originalImg
sizes
}
}
}
}
}

然后您的组件可以使用相同的查询并呈现如下结果:

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

const imgGridStyle = {
display: 'grid',
gridTemplateColumns: `repeat(auto-fill, 200px)`
};

export default ({ data }) => (
<div>
<h1>Hello gatsby-image</h1>
<div style={imgGridStyle}>
{data.allImageSharp.edges.map(edge =>
<Img fluid={edge.node.fluid} />
)}
</div>
</div>
)

export const query = graphql`
query {
allImageSharp {
edges {
node {
id
fluid(maxWidth: 200, maxHeight: 200) {
...GatsbyImageSharpFluid
}
}
}
}
}
`

您可以轻松地循环遍历 data.allImageSharp.edges.map 中的查询返回的 imageSharp 节点结果数组。然后将每个节点的 fluid 属性作为 fluid 属性传递给 gatsby-image

注意:这会渲染项目中的每个 imageSharp 节点,这可能是也可能不是您想要实现的目标。

<小时/>

要按文件夹名称过滤查询,您可以像这样调整查询:

{
allImageSharp(filter: {fileAbsolutePath: {regex: "/(myFolder)/" }}) {
edges {
node {
id
fluid(maxWidth: 200, maxHeight: 200) {
...GatsbyImageSharpFluid
}
}
}
}
}

看看 gatsby graphql reference for filter关于如何对查询执行其他类型的过滤器。

关于reactjs - 如何使用 gatsby-image 查询多个图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56437205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com