问题描述
我正在 gatsby 中从 MD 文件以编程方式创建页面。我遇到的问题是,当页面加载时,我正在使用 from gatsby-plugin-image 从所述 MD 文件的 frontmatter 中提取图像,但未呈现 img 并且我得到错误 gatsby-plugin-image] Missing图片道具
这是文件和graphql设置
echo '${params.FullHTML}'
echo '${params.ParaMETERS}'
echo "${params.ParaMETERS}"
echo "${params.FullHTML}"
我尝试了一些不同的道具,例如改变
src={post.frontmatter.image} 到 src={image},
和改变
const image = getimage(post.image) 到 const image = getimage(post.frontmatter.image)
正如你所看到的,标题工作正常,所以它必须是图像的问题。
同样,当我在 graphiql 中使用相同的查询时,它确实返回图像。
解决方法
您的形象属于 frontmatter
,因此根据您的尝试,您从未尝试过:
import React from "react";
import { graphql } from "gatsby";
import Layout from "../components/Layout";
import {Button,Card,CardBody,CardTitle } from "reactstrap";
import { GatsbyImage,getImage } from "gatsby-plugin-image";
import "../styles/main.scss";
const ProductPage = ({ data }) => {
const post = data.markdownRemark;
const image = getImage(post.image)
return (
<Layout>
<div>
<Card>
<GatsbyImage
className="card-image-top"
src={post.frontmatter.image.childImageSharp.gatsbyImageData}
alt={post.description}
placeholder="blurred"
width={500}
layout="constraint"
/>
<CardTitle>{post.frontmatter.title}</CardTitle>
<CardBody>
<div dangerouslySetInnerHTML={{ __html: post.html }} />
<Button
className="btn btn-outline-secondary float-right" color="light">Buy</Button>
</CardBody>
</Card>
</div>
</Layout>
);
};
export const query = graphql`
query($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
html
frontmatter {
title
description
image {
childImageSharp {
gatsbyImageData(
width: 500
placeholder: BLURRED
formats: [AUTO]
)
}
}
}
}
}
`;
export default ProductPage;
注意 post.frontmatter.image.childImageSharp.gatsbyImageData
中的嵌套
import React from "react";
import { graphql } from "gatsby";
import Layout from "../components/Layout";
import {Button,getImage } from "gatsby-plugin-image";
import "../styles/main.scss";
const ProductPage = ({ data }) => {
const post = data.markdownRemark;
const image = getImage(post.image)
return (
<Layout>
<div>
<Card>
<GatsbyImage
className="card-image-top"
src={post.frontmatter.image.childImageSharp.gatsbyImageData} <= should be using "IMAGE" not "SRC" SRC is used for <StaticImage> <GatsbyImage> should use "IMAGE" to call it.
alt={post.description}
placeholder="blurred"
width={500}
layout="constraint"
/>
<CardTitle>{post.frontmatter.title}</CardTitle>
<CardBody>
<div dangerouslySetInnerHTML={{ __html: post.html }} />
<Button
className="btn btn-outline-secondary float-right" color="light">Buy</Button>
</CardBody>
</Card>
</div>
</Layout>
);
};