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

A Button Deep Down چالش 5 از جلسه‌ی 33، سخت

دکمه‌ی عوض‌کننده‌ی حالت (ThemeButton) دو طبقه پایین‌تر، داخل Toolbar است و به تابع flip دسترسی ندارد. تابع را هم با کانتکست بفرست:
1. در App مقدار فرستنده را یک شیء کن: value={{ theme, flip }}
2. در Page حالت را از آن شیء بردار تا کلاس #page درست شود.
3. در ThemeButton هم theme و هم flip را بردار. دکمه با کلیک حالت را عوض کند و متنش در حالت روشن Go dark و در حالت تاریک Go light باشد.

<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(null);

function ThemeButton() {
  return <button id="flip">Go dark</button>;
}

function Toolbar() {
  return (
    <div>
      <ThemeButton />
    </div>
  );
}

function Page() {
  const theme = useContext(ThemeContext);
  return (
    <div id="page" className={"box " + theme}>
      <p>Hello!</p>
      <Toolbar />
    </div>
  );
}

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

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

  return (
    <ThemeContext.Provider value={theme}>
      <Page />
    </ThemeContext.Provider>
  );
}

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

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 33: useContext: حالت روشن و تاریک · چالش بعدی: Find the Bugs

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