The Bill چالش 4 از جلسهی 23، متوسط
دکمهها چای (3 سکه) و کیک (5 سکه) به سفارش اضافه میکنند، ولی total همیشه 0 است.
بهجای const total = 0; با یک حلقهی for ... of روی items، قیمتها را جمع بزن.
<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
.big { font-size: 40px; }
ul { list-style: none; padding: 0; }
li { margin: 6px 0; }
</style>
<div id="root" dir="ltr"></div>
<script type="text/jsx">
import { useState } from "react";
import { createRoot } from "react-dom/client";
function App() {
const [items, setItems] = useState([]);
const total = 0;
function add(name, price) {
setItems([...items, { id: items.length + 1, name: name, price: price }]);
}
return (
<div>
<button id="tea" onClick={() => add("Tea", 3)}>Tea</button>
<button id="cake" onClick={() => add("Cake", 5)}>Cake</button>
<ul id="list">
{items.map((item) => (
<li key={item.id}>{item.name}: {item.price}</li>
))}
</ul>
<p id="total" className="big">Total: {total}</p>
</div>
);
}
createRoot(document.getElementById("root")).render(<App />);
</script>
راهنما و جواب این چالش · برگشت به درس جلسهی 23: چیزهایی که حساب میشوند · چالش بعدی: Tasks Left
بیشتر بخوان: جاوااسکریپت چیست؟ از دکمهی وب تا Node.js