[英]Local img not importing through Array in JS React
我一整天都在嘗試建立一個基本的投資組合作為一個練習項目。 我有一組我想展示的示例網站。 但是,我遇到的問題是,當我嘗試通過 Web 鏈接(參見 id: 1)導入照片時,它會導入,但是當我嘗試從本地 img 文件夾導入 img 時,它沒有加載。 我嘗試使用其他兩種方法導入 img,並通過 id:2 和 id:3 顯示。
唯一似乎有效的是 id:1 但我想使用的圖像是本地存儲的。
我的數據數組:data.js
export const products = [
import theBestTestImg from "./src/assets/img/bestTest.png
{
id: 1,
img: "https://images.pexels.com/photos/3585047/pexels-photo-3585047.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=500",
link: "http://aTestSite.xyz",
},
{
id: 2,
img: "./assets/img/anotherTestImg.jpg",
link: "https://anotherTestSite.com",
},
{
id: 3,
img: {theBestTestImg},
link: "https://theBestTestSite.ca",
},
];
組合列表:ProductList.jsx
import "./productList.css";
import Product from "../product/Product";
import { products } from "../../data";
const ProductList = () => {
return (
<div className="productList">
<div className="productListTexts">
<h1 className="productListTitle">Motivate & inspire</h1>
<p className="productListDesc">
This is a creative portfolio that your work has been waiting for.
Beautiful homes, stunning portfolio styles & a whole lot more awaits
inside.
</p>
</div>
<div className="productListList">
{products.map((item) => (
<Product key={item.id} img={item.img} link={item.link} />
))}
</div>
</div>
);
};
export default ProductList;
產品.jsx
import "./product.css";
const Product = ({ img, link }) => {
return (
<div className="product">
<div className="productBrowser">
<div className="productCircle"></div>
<div className="productCircle"></div>
<div className="productCircle"></div>
</div>
<a href={link} target="_blank" rel="noreferrer">
<img src={img} alt="" className="productImg" />
</a>
</div>
);
};
export default Product;
感謝您對此的任何投入和幫助。 我仍在學習 JS 並做出反應,我真的不確定為什么我的本地圖像沒有像附加圖像中看到的那樣導入,但我的網絡鏈接卻可以。
由於webpack 捆綁您的應用程序的方式,您必須在 React 中使用 require() 本地圖像。
<img src={require(img)} alt="" className="productImg" /> // this assumes every "img" object is a path to a local image
您也可以只需要()圖像對象中的圖像以保持組件原樣:
[
{
id: 1,
img: "https://images.pexels.com/photos/3585047/pexels-photo-3585047.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=500",
link: "https://example.com",
},
{
id: 2,
img: require('./assets/img/anotherTestImg.jpg'),
link: 'https://example.com',
},
]
// ...
<img src={img} alt="" className="productImg" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.