首页 > 解决方案 > 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>
                    );
                })}

      );
 }

标签: htmlreactjsimagegatsbygatsby-image

解决方案


不要直接导入您的 JSON。相反,使用gatsby-transformer-json 获取gatsby-source-filesystem并转换它。为了让 Gatsby 自动将在 JSON 中找到的图像路径转换为实际的文件节点,这些路径应该与它们所在的 JSON 文件相关。这将允许您使用 Gatsby 的 graphql 存储来提取数据。

添加gatsby-transformer-sharp到组合中,您将能够使用 gatsby-image 组件通过延迟加载渲染完美优化的图像。更多关于这里


推荐阅读