جواب «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 باشد.
راهنما
در Page: const { theme } = useContext(ThemeContext);. در ThemeButton: const { theme, flip } = useContext(ThemeContext); و <button id="flip" onClick={flip}>{theme === "light" ? "Go dark" : "Go light"}</button>.
یک جواب درست
<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() {
const { theme, flip } = useContext(ThemeContext);
return <button id="flip" onClick={flip}>{theme === "light" ? "Go dark" : "Go light"}</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, flip }}>
<Page />
</ThemeContext.Provider>
);
}
createRoot(document.getElementById("root")).render(<App />);
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن