繼續上一回的React Props-組件屬性,今天用Array.map()方法傳遞數據,將進一步簡化 Cards 組件的傳遞數據,提高 React 應用程序性能。
1.新增一個存放資料的檔案,將資料用陣列方式表示。
const Datas = [
{
title : "Steak Meal" ,
hh3 : "upto 90% off",
imgsrc:meal,
} ,
{
title: "Hamburger" ,
hh3:"upto 80% off",
imgsrc :meal01,
} ,
{
title : "Cookies" ,
hh3:"upto 78% off",
imgsrc :meal02,
} ,
{
title : "Ice Cream" ,
hh3:"upto 70% off",
imgsrc :meal05,
} ,
]
export default Datas;
2.Card組件不需變更
import React from 'react';
const Card = (props) => {
return (
<div>
<section className="category" id="category">
<div className="box-container">
<div className="box">
<h3>{props.title}</h3>
<p>{props.hh3}</p>
<img
src={props.imgsrc} />
<a href="" class="btn">Buy now</a>
</div>
</div>
</section>
</div>
)
}
export default Card
3.在App.js中用map方法簡化程式。
const card =(val)=>{
return(
<Card
title={val.title}
hh3={val.hh3}
imgsrc ={val.imgsrc}
/>
)
}
const App = (props) => {
return (
<div>
<Header1 />
<Header2 />
{Datas.map(card)}
</div>
)
}
export default App
備註:
Array.map()用法
( https://www.w3schools.com/jsref/jsref_map.asp )