One Colour for Both چالش 5 از جلسهی 21، سخت
Box و Label هر کدام رنگ را در state خودشان دارند و دکمهها هیچ کاری نمیکنند.
رنگ را به App ببر:
- در App یک state به اسم color بساز که اولش "red" است.
- Box و Label دیگر state نداشته باشند و color را با prop بگیرند.
- هر دکمه رنگ را عوض کند: #red به "red"، #green به "green" و #blue به "blue".
<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#box { width: 120px; height: 60px; margin: 12px auto; border: 2px solid #334155; border-radius: 12px; }
</style>
<div id="root" dir="ltr"></div>
<script type="text/jsx">
import { useState } from "react";
import { createRoot } from "react-dom/client";
function Box() {
const [color, setColor] = useState("red");
return <div id="box" style={{ backgroundColor: color }}></div>;
}
function Label() {
const [color, setColor] = useState("red");
return <p id="label">{color}</p>;
}
function App() {
return (
<div>
<Box />
<Label />
<button id="red">Red</button>
<button id="green">Green</button>
<button id="blue">Blue</button>
</div>
);
}
createRoot(document.getElementById("root")).render(<App />);
</script>
راهنما و جواب این چالش · برگشت به درس جلسهی 21: state را بالا ببر · چالش بعدی: Find the Bugs
بیشتر بخوان: جاوااسکریپت چیست؟ از دکمهی وب تا Node.js