react实现信号灯
实现思路
使用React的状态管理来控制信号灯的切换逻辑,通过CSS样式实现不同颜色的灯光显示效果。
组件结构
创建SignalLight组件,包含三种颜色的灯(红、黄、绿),通过状态控制当前亮起的灯。
状态管理
使用useState和useEffect来管理当前激活的灯颜色和自动切换逻辑。
import React, { useState, useEffect } from 'react';
function SignalLight() {
const [activeLight, setActiveLight] = useState('red');
useEffect(() => {
const timer = setInterval(() => {
setActiveLight(prev => {
if (prev === 'red') return 'green';
if (prev === 'green') return 'yellow';
return 'red';
});
}, 3000); // 每3秒切换一次
return () => clearInterval(timer);
}, []);
return (
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
<div
style={{
width: 100,
height: 100,
borderRadius: '50%',
backgroundColor: activeLight === 'red' ? 'red' : 'gray',
margin: 10
}}
/>
<div
style={{
width: 100,
height: 100,
borderRadius: '50%',
backgroundColor: activeLight === 'yellow' ? 'yellow' : 'gray',
margin: 10
}}
/>
<div
style={{
width: 100,
height: 100,
borderRadius: '50%',
backgroundColor: activeLight === 'green' ? 'green' : 'gray',
margin: 10
}}
/>
</div>
);
}
export default SignalLight;
样式优化
可以添加边框和阴影效果使信号灯更逼真。
const lightStyle = {
width: 100,
height: 100,
borderRadius: '50%',
margin: 10,
border: '2px solid black',
boxShadow: '0 0 10px rgba(0,0,0,0.5)'
};
手动控制版本
如果需要手动控制信号灯切换,可以添加按钮控制。
function ManualSignalLight() {
const [activeLight, setActiveLight] = useState('red');
return (
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
<div style={{ ...lightStyle, backgroundColor: activeLight === 'red' ? 'red' : 'gray' }} />
<div style={{ ...lightStyle, backgroundColor: activeLight === 'yellow' ? 'yellow' : 'gray' }} />
<div style={{ ...lightStyle, backgroundColor: activeLight === 'green' ? 'green' : 'gray' }} />
<div style={{ marginTop: 20 }}>
<button onClick={() => setActiveLight('red')}>红</button>
<button onClick={() => setActiveLight('yellow')}>黄</button>
<button onClick={() => setActiveLight('green')}>绿</button>
</div>
</div>
);
}
动画效果
使用CSS过渡动画使灯光切换更平滑。
.light {
transition: background-color 0.5s ease;
}
完整组件
将信号灯封装为可复用的组件,支持自定义时间和颜色。
function TrafficLight({ lights = ['red', 'yellow', 'green'], duration = 3000 }) {
const [activeIndex, setActiveIndex] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setActiveIndex(prev => (prev + 1) % lights.length);
}, duration);
return () => clearInterval(timer);
}, [lights.length, duration]);
return (
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
{lights.map((color, index) => (
<div
key={color}
className="light"
style={{
...lightStyle,
backgroundColor: index === activeIndex ? color : 'gray'
}}
/>
))}
</div>
);
}






