You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用React Native+JavaScript实现基于setInterval的文本式交通灯

React Native 交通灯实现方案(仅用Text组件)

原代码的核心问题

  • 在Text组件内嵌套View不符合React Native规则,Text只能直接包含文本或嵌套其他Text组件
  • 在render里用let time=0定义变量,每次组件渲染都会重置,无法维持状态
  • setGreen函数里的文本错误写成了YELLOW
  • 未通过setInterval实现定时切换的完整逻辑

完整实现代码

import React, { Component } from 'react';
import { SafeAreaView, Text, StyleSheet } from 'react-native';

class TrafficLight extends Component {
  // 初始化状态,记录当前灯的类型、文本和颜色
  state = {
    currentLight: 'red',
    lightText: 'RED',
    lightColor: 'red'
  };

  // 定义灯的切换顺序和时长(红3秒、黄2秒、绿3秒,循环)
  lightSequence = [
    { type: 'red', text: 'RED', color: 'red', duration: 3000 },
    { type: 'yellow', text: 'YELLOW', color: 'yellow', duration: 2000 },
    { type: 'green', text: 'GREEN', color: 'green', duration: 3000 }
  ];

  componentDidMount() {
    // 组件挂载时启动定时切换逻辑
    this.startLightCycle();
  }

  componentWillUnmount() {
    // 组件卸载时清除定时器,避免内存泄漏
    clearInterval(this.lightInterval);
  }

  startLightCycle = () => {
    let currentIndex = 0;
    this.lightInterval = setInterval(() => {
      // 切换到下一个灯,循环遍历序列
      currentIndex = (currentIndex + 1) % this.lightSequence.length;
      const nextLight = this.lightSequence[currentIndex];
      this.setState({
        currentLight: nextLight.type,
        lightText: nextLight.text,
        lightColor: nextLight.color
      });
    }, this.lightSequence[currentIndex].duration);
  };

  render() {
    return (
      <SafeAreaView style={styles.container}>
        {/* 直接根据state渲染对应颜色和文本的Text组件 */}
        <Text style={{ color: this.state.lightColor, fontSize: 40, fontWeight: 'bold' }}>
          {this.state.lightText}
        </Text>
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff'
  }
});

export default TrafficLight;

关键逻辑说明

  • 用组件state维护当前灯的状态,确保状态变化时组件自动重新渲染
  • 在componentDidMount启动定时器,componentWillUnmount清除定时器,避免内存泄漏
  • 用lightSequence数组统一管理每个灯的配置,便于后续修改或扩展
  • render中直接根据state值渲染Text组件,无需嵌套多余的View,符合React Native组件嵌套规范

内容的提问来源于stack exchange,提问作者Ramanjeet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 21:40:10