[英]Pictures in “img” tag do not load
几天前我开始创建一个 web 应用程序来练习 Reacjs。 web 应用程序非常简单,它是一个 SPA,其中超级英雄将显示在图像中(本地存储,不使用数据库,使用虚假 API),具体取决于每个英雄所属的发布者。
一切都很顺利,直到我尝试加载与您的屏幕对应的图像。 但是图像没有加载,好像路径错误或图像不存在。 我已经尝试了一切,但没有任何效果。 我需要帮助来解决这个问题。
这是每个图像将单独显示的组件。
import React from 'react'
export const HeroeCard = ({
id,
superhero,
publisher,
alter_ego,
first_appearance,
characters
}) => {
console.log(id);
return (
<div className="card ms-3" style={ { maxWidth: 540 } } >
<div className="row no-gutters">
<div className="col-md-4">
<img src={ `./assets/heroes/${ id }.jpg` } className="card-img" alt={ superhero } />
</div>
</div>
</div>
)
}
该组件是每个英雄被其发布者过滤并作为过滤数据作为道具发送到“HeroesCard”组件的地方。
import React from 'react'
import { getHeroesByPublisher } from '../../selectors/getHeroesByPublisher'
import {HeroeCard} from './HeroeCard';
const HeroesList = ({ publisher }) => {
const heores = getHeroesByPublisher( publisher );
return (
<div className="card-columns" >
{
heores.map( hero => (
<HeroeCard
key={ hero.id }
{ ...hero }
/>
) )
}
</div>
)
}
export default HeroesList
最后,这里是“HeoresList”组件将被重新渲染以显示在其各自屏幕中的位置。
import React from 'react'
import HeroesList from '../heroes/HeroesList'
const MarvelScreen = () => {
return (
<>
<h1> Marvel Screen </h1>
<hr/>
<HeroesList publisher="Marvel Comics"/>
</>
)
}
export default MarvelScreen
这是执行代码时的结果图像。
还可以使用 Chrome 的开发者工具解析 HTML 属性。 并且“img”标签贡品显示正确。
最后是我的“公共”文件夹的结构。
在我看来,您有两个英雄文件夹,一个嵌套在另一个文件夹中。 尝试像这样修改 src:
<img src={ `./assets/heroes/heroes/${ id }.jpg` } className="card-img" alt={ superhero } />
<img src={ `./assets/heroes/${ id }.jpg` } className="card-img" alt={ superhero } />
当你使用.
,它是相对于原始位置的路径。 你应该使用<img src={ /assets/heroes/id.jpg } className="card-img" alt={ superhero } />
或者<img src={../../../../public/assets/heroes/id.jpg } className="card-img" alt={ superhero } />
有点长。 问答
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.