Use React to implement a traffic light controller.

By default, the red light is on for 20 seconds and the green light is on for 20 seconds and the yellow light is on for 10 seconds. The sequence is red-green-yellow-red-green-yellow. Lights =[{color: ‘# FFF ‘, duration: 10000, twinkleDuration: 5000},…]

import React, { useEffect, useState } from 'react'
import './index.scss'

function App() {
  // Define the color of the current lamp
  const [currentLight, setCurrentLight] = useState('red')
  // Define the index of the current lamp in the lamp list data
  const [lightOn, setLightOn] = useState(2)
  
  // Map of all lights
  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}]// Change the index of the current lamp in the lamp map list
  const changeLightFn = () = > {
    setLightOn((lightOn + 1) % 3)}// Light flashing method
  const twinkleFn = () = >{
    // The number of flashes
    let twinkle_count = 0;
    // Use setInterval to call the color of Settings, etc., to achieve the current light color flashing alternately on and off
    let timer = setInterval(() = >{
      // If the current value of blinking times is greater than or equal to the flashing time of the current lamp, the counter is cleared and the next lamp is placed in the list
      if (twinkle_count >= lights[lightOn].twinkleDuration/1000) {
        changeLightFn()
        setCurrentLight(' ') // Display the default gray color
        clearInterval(timer)
        return
      }
      if (twinkle_count % 2= = =0) {
        setCurrentLight(lights[lightOn].color) / / the light
      } else {
        setCurrentLight(' ') / / the lights went out
      }
      twinkle_count++ // Accumulates the current blinking times of the lamp
    }, lights[lightOn].duration)
  }

  useEffect(() = >{
    setCurrentLight(lights[lightOn].color) // Set the current light color -- on
    setTimeout(() = >{
      twinkleFn()
    }, lights[lightOn].lightTimer) // When the headlight duration is reached, start calling the blinking method
  }, [lightOn])
  
  return (
    <div>
      {
        lights.map((item, index) => {
          return (
            <p key={index}><span className={`lightThe ${item.color= = =currentLight ? item.color :"'} `} ></span></p>)})}</div>
  );
}

export default App
Copy the code
.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;
}
Copy the code