[英]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.