我正在尝试在我正在制作的购物车中显示图像,但它没有显示。我必须导入每个图像吗?我知道我的路径没问题,因为它以前有效。我认为我的product.js 文件中可能有问题,但我无法弄清楚。
这是我的 Product.js
import React, { Component, PropTypes } from 'react';
class Product extends Component {
handleClick = () => {
const { id, addToCart, removeFromCart, isInCart } = this.props;
if (isInCart) {
removeFromCart(id);
} else {
addToCart(id);
}
}
render() {
const { name, price, currency, image, url, isInCart } = this.props;
return (
<div className="product thumbnail">
<img src={image} alt="product" />
<div className="caption">
<h3>
<a href={url}>{name}</a>
</h3>
<div className="product__price">{price} {currency}</div>
<div className="product__button-wrap">
<button
className={isInCart ? 'btn btn-danger' : 'btn btn-primary'}
onClick={this.handleClick}>
{isInCart ? 'Remove' : 'Add to cart'}
</button>
</div>
</div>
</div>
);
}
}
Product.propTypes = {
id: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
price: PropTypes.number,
currency: PropTypes.string,
image: PropTypes.string,
url: PropTypes.string,
isInCart: PropTypes.bool.isRequired,
addToCart: PropTypes.func.isRequired,
removeFromCart: PropTypes.func.isRequired,
}
export default Product;
数据来自这个product.js
const data = [
{
id: 1,
name: 'Reggae Blaster',
price: 10,
currency: 'GOLD',
image: '../assets/blaster_1.png'
},
{
id: 2,
name: 'Juicy Blaster',
price: 10,
currency: 'GOLD',
image: 'images/02.jpg'
},
{
id: 4,
name: 'Full Body Reggae Armor',
price: 20,
currency: 'GOLD',
image: 'images/04.jpg'
},
{
id: 6,
name: 'Reggae Spikes Left',
price: 5,
currency: 'GOLD',
image: 'images/06.jpg'
},
{
id: 5,
name: 'Reggae Spikes Right',
price: 5,
currency: 'GOLD',
image: 'images/05.jpg'
},
{
id: 3,
name: 'Black Full Body Reggae Armor',
price: 20,
currency: 'GOLD',
image: 'images/03.jpg'
}
];
export default data;
我正在提取除图像之外的所有数据
最佳答案
假设你使用的是webpack,你需要导入图像才能显示它
<img src={require('images/06.jpg')} alt="product" />
现在您的图像数据是动态的, 直接指定导入路径如
<img src={require(image)} alt="product" />
不起作用。
但是,您可以通过使用模板文字来导入图像
<img src={require(`${image}`)} alt="product" />
所以你的代码看起来像
render() {
const { name, price, currency, image, url, isInCart } = this.props;
return (
<div className="product thumbnail">
<img src={require(`${image}`)} alt="product" />
<div className="caption">
<h3>
<a href={url}>{name}</a>
</h3>
<div className="product__price">{price} {currency}</div>
<div className="product__button-wrap">
<button
className={isInCart ? 'btn btn-danger' : 'btn btn-primary'}
onClick={this.handleClick}>
{isInCart ? 'Remove' : 'Add to cart'}
</button>
</div>
</div>
</div>
);
}
附注还要确保您的图像路径相对于您要导入它们的文件。
关于json - ReactJs中基于动态路径加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45334874/