首页 > 解决方案 > React js 有条件地将类渲染到特定的映射项

问题描述

我一直在尝试在单击时切换一个类,以便当我单击我的任务组件中的一个映射项时,我添加了“完整”类并在该项目上放置一条线(将项目从待办事项列表中划掉)。但是,在设置了当前代码后,当我单击一个元素添加类时,所有其他元素也会被划掉,反之亦然。

这是我目前的设置。“完成”类将通过任务组件中的映射项之一添加一条线。

import { Container, Row} from 'react-bootstrap';
import {Link} from 'react-router-dom';
import axios from 'axios';

const List = (props) =>{
    return(
    <div>
       <Link style={{textDecoration:'none'}} to={`/lists/${props.listId}`} > <p className="list-item">{props.item}</p></Link>
    </div>
    ) 
}

const Tasks = (props) =>{
    return(
        <div onClick={props.onClick} className={props.className} >
        <div className='task-item' >
             <p >{props.item}</p>
        </div>
        </div>
    )
}


export default class Display extends Component {
    constructor(props){
        super(props)

        this.onCompletedTask = this.onCompletedTask.bind(this);

        this.state = {
            list: [],
            tasks:[],
            complete:false
        }
    }

    componentWillUpdate(nextProps){
        axios.get(`http://localhost:8080/lists/${this.props.match.params.listId}`)
        .then(response =>{
            this.setState({
                tasks:response.data
            })
        })
    }

    componentDidMount(){


        axios.get('http://localhost:8080/lists')
        .then(response=>{
            this.setState({
                list:response.data
            })
        })
        .catch(error =>{
            console.log(error)
        });


    }


    onCompletedTask(item){

        this.setState({ complete: !this.state.complete});
    }


    listCollection(){
        return(
         this.state.list.map(item=>{
             return(<List item = {item.title} listId={item._id} key = {item._id} />)

            })
        )
    }

    taskCollection(){
        return(
            this.state.tasks.map((item, index) =>{
                return(<Tasks onClick = {()=>this.onCompletedTask(item)} className={this.state.complete ? 'complete': ''} item={item.task}  key={index}/>)
            })
        )
    }



    render() {
        return (
            <div id='main' >
                <Container>
                    <Row>
                    <div className="sidebar">
                        <h1 style={{fontSize:"25pt"}}>Lists</h1>
                        <div className="list-menu">
                           {this.listCollection()}
                        </div>
                        <form action='/new-list' method='GET'>
                            <div style={{textAlign:'center'}}>
                            <button className='list-button' style={{fontSize:'12pt', borderRadius:'5px'}}>
                                + New List
                            </button>
                            </div>
                        </form>
                    </div>
                    <div className='tasks'>
                        <h1 style={{fontSize:'25pt'}}>Tasks</h1>
                        {this.taskCollection()}
                        <form action={`/lists/${this.props.match.params.listId}/new-task`} method='GET'>
                        <button className='task-button'>
                           +
                            </button>
                        </form>
                    </div>
                    </Row>
                </Container>


            </div>
        )
    }
}

标签: javascriptreactjsevent-handling

解决方案


您的状态仅包含一个已完成值,OFC 会切换所有任务。您可以改为存储已完成任务的地图。

this.state = {
  list: [],
  tasks: [],
  complete: {}, // <--- use empty object as simple map object
}

更新onCompletedTask以存储任务的某些唯一标识属性,例如id字段

onCompletedTask(item){
  this.setState(prevState => ({
    completed: {
      ...prevState.completed, // <--- spread existing completed state
      [item.id]: !prevState.completed[item.id] // <--- toggle value
    },
  }));
}

更新。taskCollection通过 id 检查完成的地图

taskCollection = () => {
  const { completed, tasks } = this.state;
  return tasks.map((item, index) => (
    <Tasks
      onClick={() => this.onCompletedTask(item)}
      className={completed[item.id] ? "complete" : ""} // <--- check completed[item.id]
      item={item.task}
      key={index}
    />
  ))
};

编辑奇怪的pascal-9m486


推荐阅读