在terminal終端機輸入npm create vite@latest
安裝後依照指令自行取名(這裡取名sample)後選擇react jscd sample
npm i
npm run dev
安裝好環境後
//App.jsx
import Card from "./Card";
function App() {
return (
<>
<h2>Vegetable every month</h2>
<p>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Sed, quis.
</p>
<Card
title="Basic"
price={1000}
content="every week"
callToAction="免費試用"
/>
<Card
title="Pro"
price="聯繫客服"
content="every month"
callToAction="每月都有菜"
/>
</>
);
}
export default App;
//新增Card.jsx至src(與App.jsx同層)
const Card = (props) => {
return (
<>
<div className="card mb-4">
<div className="card-header">
<h4 className="my-0">{props.title}</h4>
</div>
<div className="card-body">
<h1 className="card-title">
{typeof props.price === "number" ? `$${props.price}` : props.price}
</h1>
<p>{props.content}</p>
<button type="button" className="btn btn-outline-primary">
{props.callToAction}
</button>
</div>
</div>
</>
);
};
export default Card;
//Card.jsx
const Card = ({ title, price, content, callToAction }) => {
return (
<>
<div className="card mb-4">
<div className="card-header">
<h4 className="my-0">{title}</h4> //下略
//App.jsx
import Card from "./Card";
function App() {
const products = [
//資料
{
id: 1,
title: "Basic",
price: 1000,
content: "every week",
callToAction: "免費試用",
},
{
id: 2,
title: "Pro",
price: "聯繫客服",
content: "every month",
callToAction: "每月都有菜",
},
];
return (
<>
<h2>Vegetable every month</h2>
<p>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Sed, quis.
</p>
{products.map((product) => {
return (
<Card
title={product.title}
price={product.price}
content={product.content}
callToAction={product.callToAction}
key={product.id} //記得補上key屬性(且必須唯一)
/>
);
})}
</>
);
}
export default App;
//src同層建立PrimaryButton元件
//PrimaryButton.jsx
const PrimaryButton = ({ className, callToAction }) => {
return (
<button type="button" className={`btn ${className}`}>
{callToAction}
</button>
);
};
export default PrimaryButton;
//Card.jsx
import PrimaryButton from "./PrimaryButton";
//將{content}下button改為
{title === "Pro" ? (
<PrimaryButton
className="btn-primary"
callToAction={callToAction}
/>
) : (
<PrimaryButton
className="btn-outline-primary"
callToAction={callToAction}
/>
)}