我正在尝试用GraphQL添加gatsby-image。我不需要重写我的整个启动器,我只想要加载时间的映像优化。所有的数据查询都是使用lodash完成的,所以我很困惑。我知道在documentation之后我错过了一些简单的东西。
我正在测试一个标题,看看我是否正在访问数据。
是否需要将此查询添加到gatsby-node?
import React from 'react';
import _ from 'lodash';
import { useStaticQuery, graphql } from "gatsby"
import { Layout } from '../components/index';
import { htmlToReact, safePrefix } from '../utils';
export default class Post extends React.Component {
render() {
const data = useStaticQuery(graphql`
query postInfo {
allMarkdownRemark {
edges {
node {
id
frontmatter {
content_img_path
excerpt
img_path
subtitle
title
}
}
}
}
}
`)
return (
<Layout {...this.props}>
<article className="post post-full">
<header className="post-header">
<div className="post-meta">
</div>
<h1 className="post-title">{_.get(this.props, 'pageContext.frontmatter.title')}</h1>
</header>
{_.get(this.props, 'pageContext.frontmatter.subtitle') &&
<div className="post-subtitle">
{htmlToReact(_.get(this.props, 'pageContext.frontmatter.subtitle'))}
</div>
}
<h3>{data.allMarkdownRemark.title}</h3>
{_.get(this.props, 'pageContext.frontmatter.content_img_path') &&
<div className="post-thumbnail">
<img className="thumbnail" src={safePrefix(_.get(this.props, 'pageContext.frontmatter.content_img_path'))} alt={_.get(this.props, 'pageContext.frontmatter.title')} />
</div>
}
<div className="post-content">
{htmlToReact(_.get(this.props, 'pageContext.html'))}
</div>
</article>
</Layout>
);
}
}
发布于 2020-03-31 17:45:34
allMarkdownRemark意味着您正在查询markdown,而不是图像。但你说你只是在测试。如果您的markdown测试成功,则可以确保GraphQL部件正常工作。
下面是您链接的文档中的重要代码:
import { useStaticQuery, graphql } from "gatsby"
import Img from "gatsby-image"
export default () => {
const data = useStaticQuery(graphql`
query {
file(relativePath: { eq: "images/default.jpg" }) {
childImageSharp { // gatsby-image generates this GraphQL node for you
fluid { // gatsby-image supplies this GraphQL fragment for you
...GatsbyImageSharpFluid // gatsby-image supplies this GraphQL fragment for you
}
}
}
}
`)
return (
<div>
<h1>Hello gatsby-image</h1>
<Img
fluid={data.file.childImageSharp.fluid} // the data supplied by the gatsby-image query
alt="Gatsby Docs are awesome"
/>
</div>
)
}Do I need to add this query to gatsby-node?不,你不需要。gatsby-node.js用于以编程方式生成页面。您可以独立于任何gatsby-node.js代码使用gatsby-image。
编辑
您需要通过配置数据源来告诉gatsby-image在哪里可以找到您的镜像。最简单的方法是在gatsby-config.js中使用gatsby-plugin-filesystem
{
resolve: "gatsby-source-filesystem",
options: {
path: `${__dirname}/images`,
name: "images",
},
},您的graphQL查询
{
allFile(
filter: {
sourceInstanceName: {eq: "images"} // tell graphQL where to find your images
},
sort: {fields: [childImageSharp___fluid___originalName], order: ASC})
{
edges {
node {
childImageSharp {
fluid(maxWidth: 300, quality: 50) {
originalName
...GatsbyImageSharpFluid
}
}
}
}
}
}https://stackoverflow.com/questions/60923207
复制相似问题