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

如何在ReactJS的render函数中使用开关实现条件切换渲染

修复步骤

  • 给组件添加内部state管理开关状态,默认关闭(展示活跃任务)
  • 给Material UI的Switch组件绑定checked属性和状态变更事件
  • 根据开关状态动态选择要渲染的任务数组,删除冗余的重复渲染逻辑
  • 修正任务过滤规则:关闭开关时展示未完成(completed !==1)的活跃任务,开启时展示已完成(completed ===1)的任务
import React, { Component } from "react";
import Button from "reactstrap/lib/Button";
import TodoItem from "../TodoItem/TodoItem";
import Switch from '@material-ui/core/Switch';

export default class TodoList extends Component {
  // 初始化开关状态
  constructor(props) {
    super(props);
    this.state = {
      showCompleted: false
    }
  }

  // 处理开关状态变更
  handleSwitchChange = (e) => {
    this.setState({
      showCompleted: e.target.checked
    })
  }

  // 抽离公共渲染逻辑,避免重复代码
  renderTaskItem = (task) => {
    const { handleDelete, todoDeleteMsg, editTodo } = this.props;
    return (
      <TodoItem
        key={task.id}
        title={task.title}
        description={task.description}
        handleDelete={() => handleDelete(task.id)}
        todoDeleteMsg={todoDeleteMsg}
        editTodo={() => editTodo(task.id, task.title, task.description)}
      />
    )
  }

  render() {
    const { showTaskData, clearList, todoDeleteMsg } = this.props;
    const { showCompleted } = this.state;

    // 根据开关状态过滤任务
    const filteredTasks = showCompleted 
      ? showTaskData.filter(task => task.completed === 1)
      : showTaskData.filter(task => task.completed !== 1);

    const taskList = filteredTasks.map(this.renderTaskItem);

    return (
      <ul className="list-group my-2">
        <h3 className="text-capitalize">Todo List </h3>
        <div className="d-flex justify-content-between mb-5">
          <span>{showCompleted ? '已完成任务' : '活跃任务'}</span>
          <Switch 
            checked={showCompleted}
            onChange={this.handleSwitchChange}
            inputProps={{ 'aria-label': '切换已完成/活跃任务' }}  
          />
        </div>
        {taskList}
        <Button color="danger" onClick={clearList}>
          清空全部
        </Button>
        <p className="text-danger">{todoDeleteMsg}</p>
      </ul>
    );
  }
}

如果需要关闭开关时展示全部任务,只需将过滤逻辑修改为:

const filteredTasks = showCompleted ? showTaskData.filter(task => task.completed === 1) : showTaskData

内容的提问来源于stack exchange,提问作者Arslaan Muhammad Ali

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 03:42:00