微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 GraphQL 从 GraphCMS Assets 查询特定文件

如何解决使用 GraphQL 从 GraphCMS Assets 查询特定文件

我使用 GraphCMS 作为 GatsbyJS 站点的 CMS,我想查询特定的图像文件,然后我可以在 React 组件中使用这些文件

使用 localhost:8000___grapql 时,我可以使用此路径找到我的所有资产:

{
  discord: allGraphCmsAsset(filter: {fileName: {eq: "discord_community.png"}}) {
    edges {
      node {
        localFile { 
          childImageSharp {
            fluid(maxWidth: 600) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    }
  }
}

在我名为 community.tsx 的 React 组件文件中,我试图呈现查询中定义的不和谐图像,但我似乎无法让它工作。

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

export default function CommunityPage({ allGraphCmsAsset }) {
  return (
    <Wrapper>
      <Img
          fluid={allGraphCmsAsset.discord.localFile.childImageSharp.fluid}
          fadeIn={false}
      />
    </Wrapper>
  )
}

export const imageQuery = graphql`
{
  discord: allGraphCmsAsset(filter: {fileName: {eq: "discord_community.png"}}) {
    edges {
      node {
        localFile { 
          childImageSharp {
            fluid(maxWidth: 600) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    }
  }
}`

const Wrapper = styled.div``

我应该在当前显示的大括号中输入什么?:

fluid={allGraphCmsAsset.discord.localFile.childImageSharp.fluid}

解决方法

您在 localhost:8000/___graphql 中发现的是 Gatsby 和 GraphQL 使用放置在 gatsby-config.js 中的有效文件系统/CMS 配置创建的节点。

一旦你设置了如下配置文件:

// gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: 'gatsby-source-graphcms',options: {
        endpoint: process.env.GRAPHCMS_ENDPOINT,downloadLocalImages: true,// recommended to safe build times and improve SEO
      },},],}

您将能够:

{
  allGraphCmsAsset {
    nodes {
      localFile {
        childImageSharp {
          fixed {
            ...GatsbyImageSharpFixed
          }
        }
      }
    }
  }
}

有关详细信息,请查看 docs

查询完成后,您的数据位于 props.data.queryName 中。在您的情况下,您需要将其更改为:

export default function CommunityPage({ data }) {

console.log (data.discord) //<-- Here's your data 
  return (
    <Wrapper>
      <Img
          fluid={data.discord.nodes[0].localFile.childImageSharp.fluid}
          fadeIn={false}
      />
    </Wrapper>
  )
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。