如何在reactjs中单击按钮多次显示项目?

问题描述

如您所见,单击按钮后,我将显示一个复选框及其标签。目前,我一次只能显示一个复选框。有没有办法使我可以显示多个?

import React,{Component} from 'react';
import './App.css';

class Todobody extends Component {

    state = {
        buttonPress: false,checked: false
    };

    render() {
        return (
            <div style={{marginTop:'70px'}}>
                <div className="todo__body" style={{margin:'auto'}}>
                    <h1 style={{textAlign:'center',textdecoration:'underline'}}>To-do's</h1>
                    <div className="input-group mb-3">
                        <input type="text" className="form-control" placeholder="New Task" id="task" />
                        <div className="input-group-append">
                            <a className="btn btn-danger" type="button" onClick={this.addTask}>Add</a>
                        </div>
                    </div>
                    {this.state.buttonPress? 
                        [
                            <div style={{float:'left',paddingLeft:'25px'}} className="checkBox-container">
                                <input class="form-check-input" type="checkBox" value="" id="defaultCheck1"/>
                                <label class="form-check-label" for="defaultCheck1">{document.getElementById('task').value}</label>
                            </div>
                        ]
                    : <span/>}
                </div>
            </div>
        );
    }

    addTask = () => {
        this.setState({buttonPress:true});
    }
}

export default Todobody;

解决方法

首先,为复选框创建一个单独的组件,在本例中,将其命名为复选框。您可以尝试创建一个空数组作为初始状态。然后只需将其添加到每个按钮单击。然后将数组映射到渲染方法中,为每个调用Checkbox组件:

import React,{ Component } from 'react';
import './App.css';

const Checkbox = () => {
  return (
    <div style={{ float: 'left',paddingLeft: '25px' }} className="checkbox-container">
      <input class="form-check-input" type="checkbox" value="" id="defaultCheck1" />
      <label class="form-check-label" for="defaultCheck1">{document.getElementById('task').value}</label>
    </div>
  );
}

class TodoBody extends Component {

  state = {
    tasks: [],checked: false
  };

  addTask = () => {
    const tasks = this.state.tasks;
    this.setState({ tasks: [ tasks.length,...tasks ] });
  }

  render() {
    return (
      <div style={{ marginTop: '70px' }}>
        <div className="todo__body" style={{ margin: 'auto' }}>
          <h1 style={{ textAlign: 'center',textDecoration: 'underline' }}>To-do's</h1>
          <div className="input-group mb-3">
            <input type="text" className="form-control" placeholder="New Task" id="task" />
            <div className="input-group-append">
              <a className="btn btn-danger" type="button" onClick={() => this.addTask()}>Add</a>
            </div>
          </div>
          {!!this.state.tasks.length ?
            this.state.tasks.map((task,i) => <Checkbox key={i} />)
            : <span />}
        </div>
      </div>
    );
  }
}

export default TodoBody;