返回

React 红绿灯:构建交互式交通灯的终极指南

前端

简介

在繁忙的数字世界中,创建交互式且可定制的用户界面至关重要。在这篇文章中,我们将带领您踏上用 React 构建红绿灯的旅程。我们将从单个灯组件开始,逐步扩展到一个包含多个灯的复杂系统。

单个灯组件

构建红绿灯的第一步是创建一个单个灯组件。这个组件将负责管理单个灯的颜色、持续时间和闪烁效果。我们可以使用 React 的 useState hook 来管理组件的状态,并使用 useEffect hook 来处理灯的颜色变化。

import React, { useState, useEffect } from 'react';

const TrafficLight = (props) => {
  const [color, setColor] = useState(props.color);
  const [isTwinkling, setIsTwinkling] = useState(false);

  useEffect(() => {
    if (isTwinkling) {
      const interval = setInterval(() => {
        setColor((prevColor) => (prevColor === 'red' ? 'yellow' : 'red'));
      }, props.twinkleDuration);
      return () => clearInterval(interval);
    }
  }, [isTwinkling, props.twinkleDuration]);

  return (
    <div className={`traffic-light ${color}`}>
      <div className="light"></div>
      <div className="light"></div>
      <div className="light"></div>
    </div>
  );
};

export default TrafficLight;

父组件

有了单个灯组件后,我们就可以创建一个父组件来管理多个灯。这个父组件将负责控制灯的亮灭顺序,并提供配置选项来调整灯的颜色、持续时间和闪烁效果。我们可以使用 React 的 useState hook 来管理父组件的状态,并使用 useEffect hook 来处理灯的亮灭顺序。

import React, { useState, useEffect } from 'react';
import TrafficLight from './TrafficLight';

const TrafficLights = () => {
  const [lights, setLights] = useState([
    { color: 'red', duration: 10000, twinkleDuration: 5000 },
    { color: 'yellow', duration: 3000, twinkleDuration: 2000 },
    { color: 'green', duration: 15000, twinkleDuration: 10000 },
  ]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isTwinkling, setIsTwinkling] = useState(false);

  useEffect(() => {
    if (!isTwinkling) {
      const interval = setInterval(() => {
        setCurrentIndex((prevIndex) => (prevIndex + 1) % lights.length);
      }, lights[currentIndex].duration);
      return () => clearInterval(interval);
    }
  }, [currentIndex, lights, isTwinkling]);

  return (
    <div className="traffic-lights">
      {lights.map((light, index) => (
        <TrafficLight
          key={index}
          color={light.color}
          duration={light.duration}
          twinkleDuration={light.twinkleDuration}
          isTwinkling={isTwinkling}
        />
      ))}
    </div>
  );
};

export default TrafficLights;

结语

在本文中,我们学习了如何用 React 构建一个可配置且交互式的红绿灯。我们从单个灯组件开始,逐步扩展到一个包含多个灯的复杂系统。我们还学习了如何使用 hooks 和其他 React 特性来创建动态且可复用的组件。希望您能将这些知识应用到自己的项目中,打造出更具吸引力的用户界面。