جواب «Step 1: Turn a Card» چالش 1 از جلسهی 35
سؤال
شش کارت روی صفحهاند و همه ? نشان میدهند. با کلیک، سفارش "flip" با شمارهی کارت فرستاده میشود، ولی reducer کاری نمیکند. دو کار بکن:
1. در reducer برای سفارش "flip" یک شیء تازه برگردان که action.index به آخر آرایهی open آن اضافه شده است.
2. در Tile اگر شمارهی کارت در game.open بود، بهجای ? میوهی آن کارت (CARDS[index]) را نشان بده.
راهنما
در reducer: if (action.type === "flip") { return { ...game, open: [...game.open, action.index] }; }. در Tile: const up = game.open.includes(index); و داخل دکمه {up ? CARDS[index] : "?"}.
یک جواب درست
<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#board { display: grid; grid-template-columns: repeat(3, 72px); gap: 8px; justify-content: center; }
.tile { width: 72px; height: 72px; margin: 0; font-size: 28px; border: 2px solid #334155; border-radius: 12px; background: #e2e8f0; }
.done { background: #bbf7d0; }
</style>
<div id="root" dir="ltr"></div>
<script type="text/jsx">
import { useReducer, useEffect } from "react";
import { createRoot } from "react-dom/client";
const CARDS = ["🍎", "🍌", "🍎", "🍇", "🍌", "🍇"];
const START = { open: [], done: [], moves: 0 };
function reducer(game, action) {
if (action.type === "flip") {
return { ...game, open: [...game.open, action.index] };
}
return game;
}
function useGame() {
const [game, dispatch] = useReducer(reducer, START);
function flip(index) {
dispatch({ type: "flip", index: index });
}
return { game, flip };
}
function Tile({ index, game, flip }) {
const up = game.open.includes(index);
return (
<button id={"t" + index} className="tile" onClick={() => flip(index)}>
{up ? CARDS[index] : "?"}
</button>
);
}
function App() {
const { game, flip } = useGame();
return (
<div>
<h1>Memory Game</h1>
<div id="board">
{CARDS.map((card, i) => (
<Tile key={i} index={i} game={game} flip={flip} />
))}
</div>
</div>
);
}
createRoot(document.getElementById("root")).render(<App />);
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن