javascript - 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
这是正确的方法吗?请让我知道我做错了什么或如何动态渲染这些图像。
解决方案
正如@coreyward所说,您不能props
在StaticImage
组件中使用动态,这是一个已知的限制。
也就是说,您有两个选择:
使用标准的
img
HTML 标签。使用
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] ) } } } } `
推荐阅读
- mongodb - 无法在数字海洋中的 linux Ubuntu 上启动 mongodb 作为服务
- javascript - 360 度 PNG 序列拖动
- php - 将抓取结果转换为数组
- java - 带有方法声明的非法表达式开头
- neo4j - 返回重复节点路径中的不同节点
- python - Add Label Annotations on Axes
- android - 如何保存片段更改的数据?
- java - 这可能只显示实时 Firebase 数据库的某些特定子值的列表视图吗
- sql-server - 从 SQL Server 中的逗号分隔输入变量中获取单个单词
- javascript - Redux-Thunk:异步调度不起作用