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

مثال JavaScript: <script type="text/jsx"> — useContext: حالت روشن و تاریک 2 3

مثال 4 از درس جلسه‌ی 33 آموزش ری‌اکت (React) از صفر برای نوجوانان، قطعه به قطعه: useContext: حالت روشن و تاریک

مقدار کانتکست می‌تواند از state بیاید. آن‌وقت با عوض شدن state، همه‌ی کامپوننت‌هایی که کانتکست را می‌خوانند با هم دوباره کشیده می‌شوند. این همان دکمه‌ی حالت تاریک است که در سایت‌ها می‌بینی.

<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 className={"box " + theme}>Theme: {theme}</h2>;
}

function Note() {
  const theme = useContext(ThemeContext);
  return <p 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 onClick={flip}>Change theme</button>
    </ThemeContext.Provider>
  );
}

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

این کد را همین‌جا در ویرایشگر HTML اجرا کن، عددها و متن‌هایش را عوض کن و دوباره اجرا کن تا ببینی چه تغییری می‌کند.

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

← مثال قبلی · برگشت به درس جلسه‌ی 33: useContext: حالت روشن و تاریک · مثال بعدی → · چالش‌های این جلسه