بتل کد Battle Codeدارد باز می‌شود…

مثال JavaScript: <script type="text/jsx"> — چیزهایی که حساب می‌شوند 2 3

مثال 4 از درس جلسه‌ی 23 آموزش ری‌اکت (React) از صفر برای نوجوانان، قطعه به قطعه: چیزهایی که حساب می‌شوند

جمع قیمت‌ها هم حساب‌شدنی است. با همان حلقه‌ی for ... of که بلدی، قبل از return جمع بزن. با هر خرید تازه، حلقه دوباره اجرا می‌شود.

<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; }
</style>

<div id="root" dir="ltr"></div>

<script type="text/jsx">
import { useState } from "react";
import { createRoot } from "react-dom/client";

function App() {
  const [prices, setPrices] = useState([3, 5]);

  let total = 0;
  for (const price of prices) {
    total += price;
  }

  return (
    <div>
      <p>Things: {prices.length}</p>
      <p className="big">Total: {total}</p>
      <button onClick={() => setPrices([...prices, 4])}>Buy for 4</button>
    </div>
  );
}

createRoot(document.getElementById("root")).render(<App />);
</script>

این کد را همین‌جا در ویرایشگر HTML اجرا کن، عددها و متن‌هایش را عوض کن و دوباره اجرا کن تا ببینی چه تغییری می‌کند.

بیشتر بخوان: جاوااسکریپت چیست؟ از دکمه‌ی وب تا Node.js

← مثال قبلی · برگشت به درس جلسه‌ی 23: چیزهایی که حساب می‌شوند · مثال بعدی → · چالش‌های این جلسه