html - GatsbyJs - 从 config.js 读取时图像渲染不起作用
问题描述
我有一个图像数组定义在config.js
. 使用配置文件时,我无法渲染任何图像,但原始 HTML 渲染工作正常。
配置.js
portfolioEntry: [
{
image: '../assets/images/portfolio/solo2.jpg',
service: 'Service text',
address: 'The address'
},
{}
...
]
投资组合.js
import React from "react";
import config from "../../config";
import solo2 from "../assets/images/portfolio/solo2.jpg"; // using this, it is working fine
export default function Portfolio() {
return (
{config.portfolioEntry.map((portfolio, idx) => {
const {image, service, address} = portfolio;
console.log(portfolio);
return (
<div className="box" key={idx}>
<div className="imgBx">
// this is working fine
<img className="img-fluid" src={solo2} alt="not showing"/>
// these is not working
<img className="img-fluid" src={image} alt="not showing"/>
<img className="img-fluid" src={{image}} alt="not showing"/>
</div>
<div className="content">
<h3>{service}</h3>
<p>{address}</p>
</div>
</div>
);
})}
);
}
解决方案
不要直接导入您的 JSON。相反,使用gatsby-transformer-json 获取gatsby-source-filesystem
并转换它。为了让 Gatsby 自动将在 JSON 中找到的图像路径转换为实际的文件节点,这些路径应该与它们所在的 JSON 文件相关。这将允许您使用 Gatsby 的 graphql 存储来提取数据。
添加gatsby-transformer-sharp
到组合中,您将能够使用 gatsby-image 组件通过延迟加载渲染完美优化的图像。更多关于这里。
推荐阅读
- php - 新创建的文件夹不显示 Wordpress
- vaadin - 最新的 Vaadin Start 生成的应用程序 - 带有流/混合视图的主布局主题中的错误?
- pandas - 避免 python/pandas 中的循环
- xpath - 使用 xpath 访问节点之前的文本
- python - 二分变量与连续变量的相关性
- r - 我们可以在 knitr kable 函数中使用胶水函数吗?
- azure - 已删除 UP 设备中的任务移至新添加的设备
- node.js - Node JS:升级订阅时,Stripe 支付意图为空
- python - 在 MS Access 中使用 to_sql(... , method='multi') 时出错
- c++ - 显式模板实例化示例