站长资讯网
最全最丰富的资讯网站

react怎么实现红绿灯

react实现红绿灯的方法:1、引入“import React, { useEffect, useState } from 'react'”;2、创建“function App() {…}”方法;3、定义所有灯信息map;4、定义灯闪烁的方法为“const twinkleFn = ()=>{…}”;5、设置红绿黄颜色样式即可。

react怎么实现红绿灯

本教程操作环境:Windows10系统、react18.0.0版、Dell G3电脑。

react怎么实现红绿灯?

用React实现红绿灯

用 React 实现一个信号灯(交通灯)控制器,要求:

默认情况下,红灯亮20秒,并且最后5秒闪烁绿灯亮20秒,并且最后5秒闪烁黄灯亮10秒, 次序为:红-绿-黄-红-绿-黄。 灯的个数、颜色、持续时间、闪烁时间、灯光次序都可配置,如:lights=[{color: '#fff', duration: 10000, twinkleDuration: 5000}, … ]

import React, { useEffect, useState } from 'react' import './index.scss' function App() {   // 定义当前灯的颜色   const [currentLight, setCurrentLight] = useState('red')   // 定义当前灯在灯列表数据中的index   const [lightOn, setLightOn] = useState(2)      // 所有灯信息map   const lights=[     {       color: 'red',        lightTimer: 5000,       duration: 1000,        twinkleDuration: 5000     },     {       color: 'green',        lightTimer: 4000,       duration: 1000,        twinkleDuration: 5000     },     {       color: 'yellow',        lightTimer: 3000,       duration: 1000,        twinkleDuration: 0     }   ]      // 改变当前灯在灯map列表的index   const changeLightFn = () => {     setLightOn((lightOn + 1) % 3)   }      // 灯闪烁的方法   const twinkleFn = ()=>{     // 闪烁的次数     let twinkle_count = 0;     // 用setInterval定时调用设置等的颜色,实现当前灯颜色亮灭交替闪烁     let timer = setInterval(()=>{       // 如果闪烁次数的当前值大于等于当前灯的闪烁时间,就清除计数器,进入下一个灯的列表位置       if (twinkle_count >= lights[lightOn].twinkleDuration/1000) {         changeLightFn()         setCurrentLight('') // 等的颜色清空,显示默认灰色         clearInterval(timer)         return       }       if (twinkle_count % 2 === 0) {         setCurrentLight(lights[lightOn].color) // 灯亮       } else {         setCurrentLight('') // 灯灭       }       twinkle_count++ // 灯的当前闪烁次数累加     }, lights[lightOn].duration)   }   useEffect(()=>{     setCurrentLight(lights[lightOn].color) // 设置当前灯的颜色 -- 灯亮     setTimeout(()=>{       twinkleFn()     }, lights[lightOn].lightTimer) // 当达到前灯亮持续的时间,开始调用灯闪烁的方法   }, [lightOn])      return (     <div>       {         lights.map((item, index) => {           return (             <p key={index}><span className={`light ${item.color === currentLight ? item.color : ''}`}></span></p>           )         })       }     </div>   ); } export default App
登录后复制

.light {     display: inline-block;     width: 100px;     height: 100px;     border-radius: 50%;     background: gray; } .red {     background-color: red; } .green {     background-color: green; } .yellow {     background-color: yellow; }
登录后复制

推荐学习:《react视频教程》

赞(0)
分享到: 更多 (0)