【发布时间】:2020-09-03 10:58:01
【问题描述】:
我有以下文件夹结构:
- React-app>public>img(有无法加载的 png 图像)
- React-app>src>components(有一个需要渲染图片的组件)
- React-app>data.js 看起来像这样(注意这些是完整代码的 sn-ps):
export const storeProducts = [
{
id: 1,
title: "Google Pixel - Black",
img: "../../public/img/product-1.png",
price: 10,
company: "GOOGLE",
info:
"Lorem ipsum dolor amet offal butcher quinoa sustainable gastropub, echo park actually green juice sriracha paleo. Brooklyn sriracha semiotics, DIY coloring book mixtape craft beer sartorial hella blue bottle. Tote bag wolf authentic try-hard put a bird on it mumblecore. Unicorn lumbersexual master cleanse blog hella VHS, vaporware sartorial church-key cardigan single-origin coffee lo-fi organic asymmetrical. Taxidermy semiotics celiac stumptown scenester normcore, ethical helvetica photo booth gentrify.",
inCart: false,
count: 0,
total: 0
},
尝试渲染图像的组件如下所示:
import React, { Component } from 'react';
import styled from 'styled-components';
import { Link } from 'react-router-dom';
import { ProductConsumer } from '../context';
import PropTypes from "prop-types";
class Product extends Component {
render() {
const { id, title, img, price, inCart } = this.props.product;
console.log(img);
return (
<ProductWrapper className="col-9 mx-auto col-md-6 col-lg-3 my-3">
<div className="card">
<ProductConsumer>
{(value) => (
<div className="img-container p-5"
onClick={() => value.handleDetail(id)}>
<Link to="/details">
<img src={img} alt="product" className="card-img-top" />
</Link>
我尝试将 img 文件夹移动到不同的路径中。我尝试将上面的 img src 更改为直接引用图像而不是 {img} 对象。控制台日志输出图像的路径。
我不确定是否应该使图像的路径相对于 data.js 或 product.js,但我都尝试过。我有点确信路径不是问题,因为即使直接从组件中引用图像也不起作用。
我已经用 Google 搜索并搜索过,但没有找到任何有用的信息。
我错过了什么?
编辑:我想诀窍是使路径相对于公用文件夹。这就是为我做的。
【问题讨论】:
-
我希望您使用某种捆绑器(如 webpack)来运行开发环境。在这种情况下,webpack 应该指向公共文件夹,并且图像路径应该来自公共路径,例如
/img/product-1.png -
谢谢,我没有使用 WebPack。有没有办法在不使用 WebPack 的情况下做到这一点?
-
取决于你如何捆绑 js 文件。你用什么 ?捆绑器开发服务器将能够执行与上述相同的操作。
-
看起来你的图片路径不正确,
./public/img/image.path因为你的 data.js 在你的应用的根路径中 -
正如@Panther 所说,试试
img: "/img/product-1.png",这是假设大多数服务器都可以从根路径访问公共文件夹文件。
标签: javascript reactjs