Step 2: Answer and Score چالش 2 از جلسهی 40، متوسط
حالا گزینهها باید کار کنند.
1. در App دو state تازه بساز: index (شمارهی سؤال، از 0) و score (امتیاز، از 0).
2. تابع pick(i) را بنویس: اگر i با answer سؤال فعلی یکی بود، یک امتیاز اضافه کند. بعد اگر سؤال دیگری مانده بود، index را یکی زیاد کند.
3. Quiz این props را هم بگیرد: number، total، score و onPick. بالای سؤال یک p با id برابر progress بنویسد Question 1 of 3 و زیر گزینهها یک p با id برابر score بنویسد Score: 0. هر دکمه با کلیک onPick(i) را صدا بزند.
<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
.card { max-width: 260px; margin: 12px auto; padding: 16px; border: 2px solid #334155; border-radius: 16px; background: #f8fafc; }
.row { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; }
.option { min-width: 90px; }
.right { background: #bbf7d0; }
.wrong { background: #fecaca; }
</style>
<div id="root" dir="ltr"></div>
<script type="text/jsx">
import { useState } from "react";
import { createRoot } from "react-dom/client";
const QUESTIONS = [
{ id: 1, text: "What colour is the sky?", options: ["Green", "Blue", "Red"], answer: 1 },
{ id: 2, text: "How many legs does a spider have?", options: ["Eight", "Six", "Ten"], answer: 0 },
{ id: 3, text: "Which planet do we live on?", options: ["Mars", "Venus", "Earth"], answer: 2 },
];
function Start({ onStart }) {
return (
<div id="start-screen" className="card">
<h1>Sky Quiz</h1>
<p>{QUESTIONS.length} questions</p>
<button id="start" onClick={onStart}>Start</button>
</div>
);
}
function Quiz({ question }) {
return (
<div id="quiz" className="card">
<h2 id="question">{question.text}</h2>
<div className="row">
{question.options.map((option, i) => (
<button key={option} id={"opt" + i} className="option">{option}</button>
))}
</div>
</div>
);
}
function App() {
const [screen, setScreen] = useState("start");
if (screen === "start") {
return <Start onStart={() => setScreen("quiz")} />;
}
return <Quiz question={QUESTIONS[0]} />;
}
createRoot(document.getElementById("root")).render(<App />);
</script>
راهنما و جواب این چالش · برگشت به درس جلسهی 40: پروژه: کوییز من با ریاکت · چالش بعدی: Step 3: The Result Screen
بیشتر بخوان: جاوااسکریپت چیست؟ از دکمهی وب تا Node.js