首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用GraphQL从GraphCMS Assets查询特定文件

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

Stack Overflow用户
提问于 2021-02-03 19:11:19
回答 1查看 272关注 0票数 1

我使用GraphCMS作为我的GatsbyJS站点的内容管理系统,我想查询特定的图像文件,然后我可以在React组件中使用它。

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

代码语言:javascript
复制
{
  discord: allGraphCmsAsset(filter: {fileName: {eq: "discord_community.png"}}) {
    edges {
      node {
        localFile { 
          childImageSharp {
            fluid(maxWidth: 600) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    }
  }
}

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

代码语言:javascript
复制
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``

我应该在当前显示的curley括号中键入什么内容?:

代码语言:javascript
复制
fluid={allGraphCmsAsset.discord.localFile.childImageSharp.fluid}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-03 20:50:27

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

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

代码语言:javascript
复制
// 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
      },
    },
  ],
}

您将能够:

代码语言:javascript
复制
{
  allGraphCmsAsset {
    nodes {
      localFile {
        childImageSharp {
          fixed {
            ...GatsbyImageSharpFixed
          }
        }
      }
    }
  }
}

有关更多详细信息,请查看docs

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

代码语言:javascript
复制
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>
  )
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66026305

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档