不久前,我跟随本教程实现了MDX帖子中的图像嵌入。请参见堆栈溢出上的这个查询以获取上下文。
使用以下内容的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
}
}
}
}
}
`如何将图像嵌入到新的设置中?
发布于 2022-09-09 02:23:55
从v4开始,我也一直在努力解决这个问题。下面是我的发现:
模板文件中的graphql查询结果可以通过props.data.mdx从MDX文件中访问
因此,在您的例子中,您可以使用mdx内部的GatsbyImage来呈现您的图像,如下所示(确保它放在您的前端下面)
import { getImage, GatsbyImage } from "gatsby-plugin-image";
<GatsbyImage
alt="alt text"
image={getImage(props.data.mdx.frontmatter.embedded)}/>https://stackoverflow.com/questions/73463825
复制相似问题