[英]Not able to display images in <img> tag in Reactjs when i have images in Array of objects
I am unable to display images in img tag in Reactjs我无法在 Reactjs 的 img 标签中显示图像
<ul className="products">
{products.map((product) => (
<li key={product._id}>
<div className="product">
<Link to={"/product/" + product._id}>
<img className="product-image" src={product.image} alt="product" />
</Link>
<div className="product-name">
<Link to={"/product/" + product._id}>{product.name}</Link>
</div>
<div className="product-brand">{product.brand}</div>
<div className="product-price">${product.price}</div>
<div className="product-rating">
{product.rating} Stars ({product.numReviews} Reviews)
</div>
</div>
</li>
))}
</ul>
Every other data like product.name, product.price etc is getting displayed but problem lies with product.image.所有其他数据,如 product.name、product.price 等都会显示,但问题出在 product.image 上。
The above pic shows my products array.上图显示了我的产品数组。
The above pic shows each component the page上图显示了页面的每个组件
These issue appears since React is using webpack as bundler by default.出现这些问题是因为 React 默认使用 webpack 作为捆绑器。 When using assets with the bundler you should provide the image path with
require('...')
or directly import the asset as a module with import
将资产与捆绑器一起使用时,您应该使用
require('...')
提供图像路径,或者使用 import 直接将资产作为模块import
In your case <img className="product-image" src={product.image} alt="product" />
should be changed to在你的情况下
<img className="product-image" src={product.image} alt="product" />
应该改为<img className="product-image" src={require(product.image)} alt="product" />
or you should restructure your array of objects so that the product.image is a valid path. <img className="product-image" src={require(product.image)} alt="product" />
或者您应该重组对象数组,使 product.image 成为有效路径。
I would suggest changing the place where the images are stored to a separate asset folder for a clearer structure instead of referring to them from the root folder我建议将图像存储位置更改为单独的资产文件夹以获得更清晰的结构,而不是从根文件夹中引用它们
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.