react實(shí)現(xiàn)紅綠燈的方法:1、引入“import React, { useEffect, useState } from 'react'”;2、創(chuàng)建“function App() {…}”方法;3、定義所有燈信息map;4、定義燈閃爍的方法為“const twinkleFn = ()=>{…}”;5、設(shè)置紅綠黃顏色樣式即可。
本教程操作環(huán)境:Windows10系統(tǒng)、react18.0.0版、Dell G3電腦。
react怎么實(shí)現(xiàn)紅綠燈?
用React實(shí)現(xiàn)紅綠燈
用 React 實(shí)現(xiàn)一個(gè)信號(hào)燈(交通燈)控制器,要求:
默認(rèn)情況下,紅燈亮20秒,并且最后5秒閃爍綠燈亮20秒,并且最后5秒閃爍黃燈亮10秒, 次序?yàn)椋杭t-綠-黃-紅-綠-黃。 燈的個(gè)數(shù)、顏色、持續(xù)時(shí)間、閃爍時(shí)間、燈光次序都可配置,如:lights=[{color: '#fff', duration: 10000, twinkleDuration: 5000}, … ]
import React, { useEffect, useState } from 'react' import './index.scss' function App() { // 定義當(dāng)前燈的顏色 const [currentLight, setCurrentLight] = useState('red') // 定義當(dāng)前燈在燈列表數(shù)據(jù)中的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 } ] // 改變當(dāng)前燈在燈map列表的index const changeLightFn = () => { setLightOn((lightOn + 1) % 3) } // 燈閃爍的方法 const twinkleFn = ()=>{ // 閃爍的次數(shù) let twinkle_count = 0; // 用setInterval定時(shí)調(diào)用設(shè)置等的顏色,實(shí)現(xiàn)當(dāng)前燈顏色亮滅交替閃爍 let timer = setInterval(()=>{ // 如果閃爍次數(shù)的當(dāng)前值大于等于當(dāng)前燈的閃爍時(shí)間,就清除計(jì)數(shù)器,進(jìn)入下一個(gè)燈的列表位置 if (twinkle_count >= lights[lightOn].twinkleDuration/1000) { changeLightFn() setCurrentLight('') // 等的顏色清空,顯示默認(rèn)灰色 clearInterval(timer) return } if (twinkle_count % 2 === 0) { setCurrentLight(lights[lightOn].color) // 燈亮 } else { setCurrentLight('') // 燈滅 } twinkle_count++ // 燈的當(dāng)前閃爍次數(shù)累加 }, lights[lightOn].duration) } useEffect(()=>{ setCurrentLight(lights[lightOn].color) // 設(shè)置當(dāng)前燈的顏色 -- 燈亮 setTimeout(()=>{ twinkleFn() }, lights[lightOn].lightTimer) // 當(dāng)達(dá)到前燈亮持續(xù)的時(shí)間,開始調(diào)用燈閃爍的方法 }, [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
登錄后復(fù)制
.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; }
登錄后復(fù)制
推薦學(xué)習(xí):《react視頻教程》