React Js - 获取 json 数组图像到 JSX 页面动态反应


state = {
products: [
{
img: "'./images/heartstud.jpg'",
name: "Heart Earrings",
price: "1.99",
total: "3.98",
count: 2,
description:
"Yellow Chimes Crystals from Classic Designer Gold Plated Stylish Hoop Earrings for Women and Girls",
},
{
img: "./images/heartstud.jpg",
name: "Orange",
attribution: "visualhunt",
price: "0.99",
count: 1,
description:
"PANASH Woman's Stylish/Fashion Gold-plated Beaded Handcrafted Chandbalis Trendy Party/Festive/Wedding Wear Earrings",
},
{
img: "./images/heartstud.jpg",
name: "Pear",
price: "6.00",
count: 4,
description:
"Valentine Gift By Shining Diva Italian Designer Non Precious Metal Jewellery Set for Women",
},
],
};

我的 HTML 是这样的,我想从上面的产品 JSON 数组调用图像,但使用它需要我只能静态地提供它,而不是从数组中给出

<div class="row">
{this.state.products.map((product) => (
<div class="col-lg-4 col-md-6 mb-4">
<div class="card h-100">
<a href="#">
<img class="card-img-top" src={require("./images/ring.jpg")} alt="" />
</a>
<div class="card-body">
<h4 class="card-title">
<a href="#">{product.name}</a>
</h4>
<h5>${product.price}</h5>
<p class="card-text">{product.description}</p>
</div>
</div>
</div>
))}
</div>;

代替静态Imageurl我想使用{product.img}作为其他元素的使用。使用require我能够获得静态图像,但无法从状态json数据映射...请帮忙。

class App extends React.Component {
constructor(props) {
super(props);
this.state = {
products: [
{
img: "https://via.placeholder.com/600/92c952",
name: "Heart Earrings",
price: "1.99",
total: "3.98",
count: 2,
description:
"Yellow Chimes Crystals from Classic Designer Gold Plated Stylish Hoop Earrings for Women and Girls"
},
{
img: "https://via.placeholder.com/600/771796",
name: "Orange",
attribution: "visualhunt",
price: "0.99",
count: 1,
description:
"PANASH Woman's Stylish/Fashion Gold-plated Beaded Handcrafted Chandbalis Trendy Party/Festive/Wedding Wear Earrings"
},
{
img: "https://via.placeholder.com/600/771766",
name: "Pear",
price: "6.00",
count: 4,
description:
"Valentine Gift By Shining Diva Italian Designer Non Precious Metal Jewellery Set for Women"
}
]
};
}
render() {
return (
<div class="row">
{this.state.products.map(product => (
<div class="col-lg-4 col-md-6 mb-4">
<div class="card h-100">
<img
class="card-img-top"
src={product.img}
alt=""
width="100px"
/>
<div class="card-body">
<h4 class="card-title">{product.name}</h4>
<h5>${product.price}</h5>
<p class="card-text">{product.description}</p>
</div>
</div>
</div>
))}
</div>
);
}
}
export default App;

检查一下它是否工作正常。无需添加迭代要求。工作链接点击这里

使用 Webpack 时(假设您使用 CRA 引导您的项目(,像./images/ring.jpg这样的路径仅在构建时可用。

在运行时,使用:

// product.img = "./images/heartstud.jpg";
<img class="card-img-top" src={require(product.img)} alt="" />

或事先导入路径:

import heartstud from "./images/heartstud.jpg";
// v generated from webpack in build
console.log(heartstud); // /heartstud.84287d09.jpg
state = {
products: [
{
img: heartstud,
},
],
};
<img class="card-img-top" src={product.img} alt="" />

请参阅在 CRA 中添加图像。

请注意,您有一个错别字:"./images/heartstud.jpg"(额外的'(

最新更新