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

React中使用array.map渲染列表:实现可切换文字颜色功能

React 彩色列表组件实现方案

咱们来把这个能切换文字颜色的列表组件完善好,直接上完整的可运行代码:

import React, { Component } from "react";

class List extends Component {
  constructor(props) {
    super(props);
    // 初始化颜色状态,默认红色
    this.state = { color: 'red' };
    // 绑定方法到组件实例
    this.toggleColor = this.toggleColor.bind(this);
  }

  // 颜色切换逻辑:循环切换三种颜色
  toggleColor() {
    this.setState(prevState => {
      const colorMap = {
        red: 'blue',
        blue: 'green',
        green: 'red'
      };
      return { color: colorMap[prevState.color] };
    });
  }

  render() {
    const { items } = this.props;
    const { color } = this.state;

    return (
      <div>
        {/* 颜色切换按钮,显示当前颜色 */}
        <button onClick={this.toggleColor}>
          切换颜色(当前:{color})
        </button>
        {/* 渲染列表,绑定颜色样式 */}
        <ul style={{ listStyle: 'none', paddingLeft: 0 }}>
          {items.map((value, index) => (
            <li 
              key={index} 
              style={{ color: color, margin: '8px 0', fontSize: '18px' }}
            >
              {value}
            </li>
          ))}
        </ul>
      </div>
    );
  }
}

// 父组件使用示例
function App() {
  const sampleItems = ['苹果', '香蕉', '橙子', '草莓'];
  return <List items={sampleItems} />;
}

export default App;

关键部分说明:

  • 状态管理:组件内部用state维护当前文字颜色,初始值设为red,确保渲染时有默认颜色。
  • 颜色切换方法:toggleColor里用了函数式更新setState,这样能拿到上一次的状态值,避免状态更新依赖问题。我们定义了一个颜色映射表,实现红色→蓝色→绿色→红色的循环切换。
  • 列表渲染:直接在render里遍历props.items数组,给每个<li>元素加上key(这里用索引,实际项目里建议用唯一ID),并通过style属性绑定state.color,实现文字颜色随状态变化。
  • 按钮交互:按钮绑定onClick事件到toggleColor,点击时触发状态更新,页面会自动重新渲染,列表文字颜色跟着变化。

使用注意:

  • 父组件使用时,需要通过items属性传入字符串数组,比如示例里的sampleItems。
  • 如果需要更多颜色选项,只需要扩展colorMap里的键值对就行,比如加上purple: 'orange'之类的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:15:12