https://www.youtube.com/watch?v=KuUyZEPeu5s
신호등이 점멸하는 코드를 짜보기
/* Lamp.js /
export default function Lamp({ size, color, active }) {
return (
<div
style={{
width: size,
height: size,
borderRadius: size / 2,
backgroundColor: active ? color : "#ccc",
margin: "10px auto",
transition: "background-color 0.5s",
border: "2px solid black" // 테두리 추가
}}
/>
);
}
/* TrafficLight.js /
import { useEffect, useState } from "react";
import Lamp from "./Lamp";
export default function TrafficLight({ size, timer }) {
const [activeLamp, setActiveLamp] = useState(0); // 0: red, 1: green, 2: yellow
const colors = ["red", "green", "yellow"];
useEffect(() => {
const interval = setInterval(() => {
setActiveLamp((prev) => (prev + 1) % 3);
}, timer);
return () => clearInterval(interval); // Cleanup interval on component unmount
}, [timer]);
return (
<div style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
backgroundColor: "black",
padding: "10px",
borderRadius: "10px",
width: size * 1.2,
height: size * 4
}}>
{colors.map((color, index) => (
<Lamp key={color} size={size} color={color} active={index === activeLamp} />
))}
</div>
);
}
/* App.js /
import TrafficLight from "./TrafficLight";
export default function App() {
return (
<div style={{ display: "flex", justifyContent: "space-around", padding: "20px" }}>
<TrafficLight size={150} timer={1000} /> {/* 큰 신호등 */}
<TrafficLight size={100} timer={1000} /> {/* 중간 신호등 */}
<TrafficLight size={50} timer={1000} /> {/* 작은 신호등 */}
</div>
);
}