【问题标题】:How do I query for gatsby-image?如何查询 gatsby-image?
【发布时间】:2020-06-09 17:36:26
【问题描述】:
我正在尝试查询棱镜单一类型以通过 gatsby-image 显示照片。在 GraphiQL 中搞乱之后,我看到了图像 url,但我不确定如何将其插入 gatsby-image。有什么建议吗?
<Layout
location={`home`}
image={data.prismic._allDocuments.edges.node.hero_image.childImageSharp.fluid}
>
【问题讨论】:
标签:
reactjs
gatsby
prismic.io
gatsby-image
【解决方案1】:
任何时候你在 GraphQL 中看到前缀 all,你都应该假设它会返回一个数组。
在GraphQL 中,我们可以看到_allDocuments.edges 返回array 的edges。如果我们想显示该数组中的所有内容,我们需要对其进行映射。
如果我们知道我们想要的单个事物的索引,我们可以直接使用bracket notation 访问它。
// ./pages/index.js
import React from "react"
import Layout from "../components/layout"
const IndexPage = ({data}) => {
return (
<Layout>
<ul>
{data.allFile.edges.map((edge) => (
<li>{edge.node.name}</li>
))}
</ul>
</Layout>
)}
export default IndexPage
export const query = graphql`
query HomePageQuery {
allFile(filter: {relativePath: {regex: "/png$/"}}) {
edges {
node {
id
name
relativePath
publicURL
childImageSharp {
fixed(width: 111) {
...GatsbyImageSharpFixed
}
}
}
}
}
}
`
然后你可以只 import Img from "gatsby-image" 并将相关的查询值传递给 <Img /> 组件的固定或流体属性。
// ./pages/index.js
import React from "react"
import Layout from "../components/layout"
import Img from "gatsby-image"
const IndexPage = ({data}) => {
return (
<Layout>
{data.allFile.edges.map((edge) => (
<Img fixed={edge.node.childImageSharp.fixed} />
))}
</Layout>
)}
export default IndexPage
export const query = graphql`
query HomePageQuery {
allFile(filter: {relativePath: {regex: "/png$/"}}) {
edges {
node {
id
name
relativePath
publicURL
childImageSharp {
fixed(width: 111) {
...GatsbyImageSharpFixed
}
}
}
}
}
}
`