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

جواب «Light and Dark» چالش 3 از جلسه‌ی 33

سؤال

دکمه‌ی Change theme باید حالت صفحه را بین light و dark عوض کند، ولی فرستنده همیشه "light" را پخش می‌کند.
1. در App یک state به اسم theme با مقدار اول "light" بساز.
2. تابع flip را بنویس که آن را بین "light" و "dark" عوض کند، و به دکمه بده.
3. value فرستنده را از state بگیر.

راهنما

const [theme, setTheme] = useState("light"); و function flip() { setTheme(theme === "light" ? "dark" : "light"); }. بعد value={theme} و onClick={flip}.

یک جواب درست

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
.dark { background: #1e293b; color: white; }
.light { background: #f8fafc; color: #0f172a; }
.dark { background: #1e293b; color: white; }
.box { max-width: 260px; margin: 8px auto; padding: 12px; border: 2px solid #64748b; border-radius: 12px; }
</style>

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

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

const ThemeContext = createContext("light");

function Title() {
  const theme = useContext(ThemeContext);
  return <h2 id="title" className={"box " + theme}>Theme: {theme}</h2>;
}

function Note() {
  const theme = useContext(ThemeContext);
  return <p id="note" className={"box " + theme}>This note follows the theme.</p>;
}

function App() {
  const [theme, setTheme] = useState("light");

  function flip() {
    setTheme(theme === "light" ? "dark" : "light");
  }

  return (
    <ThemeContext.Provider value={theme}>
      <Title />
      <Note />
      <button id="flip" onClick={flip}>Change theme</button>
    </ThemeContext.Provider>
  );
}

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

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن