[英]How to embed images in frontmatter with gatsby-plugin-mdx v4?
不久前,我按照本教程在 MDX 帖子中實現圖像嵌入。 有關上下文,請參閱 Stack Overflow 上的此查詢。
使用此的 v3 示例模板:
/* Post.jsx @ gatsby-plugin-mdx v3 */
import React from "react"
import { graphql } from "gatsby"
import { MDXRenderer } from "gatsby-plugin-mdx"
import Layout from "@layouts/Layout"
import { postContainer } from "@modules/Post.module.scss"
export default function DefaultPostTemplate({ data, location }) {
const post = data.mdx
return (
<Layout location={location} title={post.frontmatter.title} description={post.frontmatter.lead}>
<article className={postContainer}>
<MDXRenderer thumbnail={post.frontmatter.thumbnail} embedded={post.frontmatter.embedded}>
{post.body}
</MDXRenderer>
</article>
</Layout>
)
}
export const data = graphql`
query ($id: String!) {
mdx(id: { eq: $id }) {
id
body
frontmatter {
key
title
computerDate: date(formatString: "YYYY-MM-DD")
humanDate: date(formatString: "D. MMMM YYYY", locale: "nn")
enHumanDate: date(formatString: "MMMM D, YYYY", locale: "en")
lead
label
subtitle
embedded {
childImageSharp {
gatsbyImageData
}
}
}
}
}
`
如您所見,我將embedded
屬性傳遞給MDXProvider
組件。
但是,使用gatsby-plugin-mdx
v4 設置,我不知道該怎么做——
/* Post.jsx @ gatsby-plugin-mdx v4 */
import React from "react"
import { graphql } from "gatsby"
import Layout from "@layouts/Layout"
import { postContainer } from "@modules/Post.module.scss"
export default function DefaultPostTemplate({ data, children }) {
const post = data.mdx
return (
<Layout title={post.frontmatter.title} description={post.frontmatter.lead}>
<article className={postContainer}>
{children}
</article>
</Layout>
)
}
export const data = graphql`
query ($id: String!) {
mdx(id: { eq: $id }) {
frontmatter {
key
title
computerDate: date(formatString: "YYYY-MM-DD")
humanDate: date(formatString: "D. MMMM YYYY", locale: "nn")
lead
label
subtitle
embedded {
childImageSharp {
gatsbyImageData
}
}
}
}
}
`
如何使用新設置將圖像嵌入為 frontmatter?
自 v4 以來,我也一直在為此苦苦掙扎。 這是我發現的:
模板文件中的 graphql 查詢結果可通過props.data.mdx
從 MDX 文件中訪問
所以在你的情況下,你可以在你的 mdx 中使用GatsbyImage
來渲染你的圖像,如下所示(確保它位於你的 frontmatter 下方)
import { getImage, GatsbyImage } from "gatsby-plugin-image";
<GatsbyImage
alt="alt text"
image={getImage(props.data.mdx.frontmatter.embedded)}/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.