جواب «Find the Bugs» چالش 6 از جلسهی 33
سؤال
با دکمهی Change theme باید هم کارت #panel و هم نشان #tag بین light و dark عوض شوند. ولی برنامه دو اشتباه دارد و هیچکدام درست کار نمیکند. هر دو را پیدا و درست کن.
راهنمایی: به اسم ویژگی فرستنده نگاه کن، و به اینکه چه چیزی داخل فرستنده است و چه چیزی بیرونش.
راهنما
ویژگی فرستنده باید value باشد: value={theme}. <Badge /> را هم به داخل Provider ببر.
یک جواب درست
<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 Card() {
const theme = useContext(ThemeContext);
return <p id="panel" className={"box " + theme}>Card: {theme}</p>;
}
function Badge() {
const theme = useContext(ThemeContext);
return <p id="tag" className={"box " + theme}>Badge: {theme}</p>;
}
function App() {
const [theme, setTheme] = useState("light");
function flip() {
setTheme(theme === "light" ? "dark" : "light");
}
return (
<div>
<ThemeContext.Provider value={theme}>
<Card />
<Badge />
</ThemeContext.Provider>
<button id="flip" onClick={flip}>Change theme</button>
</div>
);
}
createRoot(document.getElementById("root")).render(<App />);
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن