首页 > 解决方案 > Gatsby 中的动态渲染图像

问题描述

我正在开发基于 React、TS 和 Gatsby 的博客。

博客文章基于降价。每篇博文都有一个类似的标题,包括标题、阅读文章所需的时间以及特定博文所涉及的技术的徽标。

我在动态渲染这些图像时遇到问题。我的想法是在降价中创建这样的东西

---
path: "/fourth"
date: "2021-06-02"
title: "TypeScript - intro"
readTime: "140"
author: "Adam Kniec"
imgs: [typescript, react]
---

That's the fourth blog post

之后,我想创建一个 graphql 查询并获取 imgs 名称,如下所示:

export const postQuery = graphql`
  query BlogPostByPath($path: String!) {
    markdownRemark(frontmatter: { path: { eq: $path } }) {
      html
      frontmatter {
    path
    readTime
    title
    author
    imgs
    date
  }
}

} `;

我现在在道具中有一组图像,我想像这样渲染这些图像

{data.markdownRemark.frontmatter.imgs.map((imgPath) => {
          const imgPatha = `../images/${imgPath}`;

          return <StaticImage src={imgPatha} alt="asdasd" />;
        })}

不幸的是,盖茨比给了我警告

react_devtools_backend.js:2560 图片未加载../images/typescript

这是正确的方法吗?请让我知道我做错了什么或如何动态渲染这些图像。

标签: javascriptreactjsgatsby

解决方案


正如@coreyward所说,您不能propsStaticImage组件中使用动态,这是一个已知的限制。

也就是说,您有两个选择:

  • 使用标准的imgHTML 标签。

  • 使用GatsbyImage组件。为此,您需要在文件系统中添加图像以允许 Gatsby 创建正确的节点,然后您需要在页面/模板中查询它们。如果没有关于实现的更多细节,就不可能猜出你的代码应该是什么样子,但这个想法依赖于类似的东西:

    import { graphql } from "gatsby"
    import { GatsbyImage, getImage } from "gatsby-plugin-image"
    
    function BlogPost({ data }) {
      const image = getImage(data.blogPost.avatar)
      return (
        <section>
          <h2>{data.blogPost.title}</h2>
          <GatsbyImage image={image} alt={data.blogPost.author} />
          <p>{data.blogPost.body}</p>
        </section>
      )
    }
    
    export const pageQuery = graphql`
      query {
        blogPost(id: { eq: $Id }) {
          title
          body
          author
          avatar {
            childImageSharp {
              gatsbyImageData(
                width: 200
                placeholder: BLURRED
                formats: [AUTO, WEBP, AVIF]
              )
            }
          }
        }
      }
    `
    

推荐阅读