您好,欢迎访问一九零五行业门户网

react怎么实现红绿灯

react实现红绿灯的方法:1、引入“import react, { useeffect, usestate } from 'react'”;2、创建“function app() {...}”方法;3、定义所有灯信息map;4、定义灯闪烁的方法为“const twinklefn = ()=>{...}”;5、设置红绿黄颜色样式即可。
本教程操作环境: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视频教程》
以上就是react怎么实现红绿灯的详细内容。
其它类似信息

推荐信息