首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用gatsby v4在前端嵌入图像?

如何用gatsby v4在前端嵌入图像?
EN

Stack Overflow用户
提问于 2022-08-23 18:52:54
回答 1查看 90关注 0票数 1

不久前,我跟随本教程实现了MDX帖子中的图像嵌入。请参见堆栈溢出上的这个查询以获取上下文。

使用以下内容的v3示例模板:

代码语言:javascript
复制
/*  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设置,我不知道如何-

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

如何将图像嵌入到新的设置中?

EN

回答 1

Stack Overflow用户

发布于 2022-09-09 02:23:55

从v4开始,我也一直在努力解决这个问题。下面是我的发现:

模板文件中的graphql查询结果可以通过props.data.mdx从MDX文件中访问

因此,在您的例子中,您可以使用mdx内部的GatsbyImage来呈现您的图像,如下所示(确保它放在您的前端下面)

代码语言:javascript
复制
import { getImage, GatsbyImage } from "gatsby-plugin-image";

<GatsbyImage
  alt="alt text"
  image={getImage(props.data.mdx.frontmatter.embedded)}/>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73463825

复制
相关文章

相似问题

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