如何在ReactJS中添加和删除选择框列表

时间:2019-07-14 10:08:04

标签: javascript html css arrays reactjs

1。我只能添加和删除“值”。它不会从UI中删除,但我看到的是“添加并删除”值。我需要评估从UI(即标签)中移除的价值。

  1. 如果用户单击所选框的一个项目列表,它将在handleadd()方法内添加数据。我不需要重复的数据。

3。如果用户单击向右箭头按钮,则数据将从选择框(1)中删除,并将添加选择框(2)。

4。如果用户单击左箭头按钮,则数据将从选择框(2)中删除,并将添加选择框(1)。

class FieldForm extends React.Component {

  state = {
    itemlist:[],
    itemlist2:[]
  }
  onChange = e => {
    const newitems = [...this.state.itemlist]
    newitems.push(e.target.value);
    this.setState({
      itemlist:newitems
    });
  };


  handleadd = (data) => {
    this.setState({
      itemlist2:data
    })

  }
  handleremove= (data) => {
     console.log("remove",data)
    const newitems = [...this.state.itemlist2]

    newitems.pop(data);
    this.setState({
      itemlist2:data
    })
    console.log("data",data)
  }


  render() {

    const options = [

  {label:'Two', id:"2"
  },
 { label:'Three', id:"3"
}
,
{label:'Four', id:"4"
}]
    return (

    <select className="custom-select" onChange={this.onChange} multiple>
      {options&& options.map(item=>(  <option value={item.label}>{item.label}</option>))}

    </select>
    <div className="col-md-2 ">      
    <button onClick={()=>this.handleadd(this.state.itemlist)} class="btn btn-primary btn-block w-25 margin-bottom">
      <i class="fa fa-arrow-right"></i>
    </button>
    <button onClick={()=>this.handleremove(this.state.itemlist) }class="btn btn-primary btn-block w-25">
      <i class="fa fa-arrow-left"></i>
    </button>
    </div>

    <select className="custom-select" multiple>
      {
        this.state.itemlist2.map(item=>( <option value={item}>{item}</option>))
      }
    </select>
    )
  }
}

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

不是很干,但是这是一个非常彻底的解决方案:https://codesandbox.io/s/gifted-mestorf-gpzx5

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class FieldForm extends React.Component {
  state = {
    itemlist: [
      { label: "Two", id: "2", enabled: true },
      { label: "Three", id: "3", enabled: true },
      { label: "Four", id: "4", enabled: true }
    ],
    itemlist2: [],
    itemsToBeRemovedFromList1: [],
    itemsToBeRemovedFromList2: []
  };

  onChangeItemList1 = e => {
    const { itemlist, itemsToBeRemovedFromList1 } = this.state;
    const foundItem = itemlist.find(item => item.label == e.target.value);

    let allItems = [...itemsToBeRemovedFromList1, foundItem];

    //add item to the to be removed list
    this.setState({
      itemsToBeRemovedFromList1: [...allItems]
    });
  };

  onChangeItemList2 = e => {
    const { itemlist2, itemsToBeRemovedFromList2 } = this.state;
    const foundItem = itemlist2.find(item => item.label == e.target.value);

    //check for duplicates
    let allItems = [...itemsToBeRemovedFromList2, foundItem];

    //add item to the to be removed list
    this.setState({
      itemsToBeRemovedFromList2: [...allItems]
    });
  };

  handleadd = () => {
    const { itemlist, itemsToBeRemovedFromList1, itemlist2 } = this.state;
    const idsOfToBeRemovedItems = itemsToBeRemovedFromList1.map(
      item => item.id
    );
    const newItemList1 = itemlist.filter(
      item => !idsOfToBeRemovedItems.includes(item.id)
    );

    const newItemList2 = itemlist.filter(item =>
      idsOfToBeRemovedItems.includes(item.id)
    );

    this.setState({
      ...this.state,
      itemlist: newItemList1,
      itemlist2: [...itemlist2, ...newItemList2],
      itemsToBeRemovedFromList1: []
    });
  };

  handleremove = () => {
    const { itemlist, itemsToBeRemovedFromList2, itemlist2 } = this.state;
    const idsOfToBeRemovedItems = itemsToBeRemovedFromList2.map(
      item => item.id
    );
    const newItemList2 = itemlist2.filter(
      item => !idsOfToBeRemovedItems.includes(item.id)
    );

    const newItemList1 = itemlist2.filter(item =>
      idsOfToBeRemovedItems.includes(item.id)
    );

    this.setState({
      ...this.state,
      itemlist: [...itemlist, ...newItemList1],
      itemlist2: newItemList2,
      itemsToBeRemovedFromList2: []
    });
  };

  render() {
    const { itemlist, itemlist2 } = this.state;
    return (
      <div>
        <select
          className="custom-select"
          onChange={this.onChangeItemList1}
          multiple
        >
          {itemlist &&
            itemlist.map(item => (
              <option id={item.id} value={item.label}>
                {item.label}
              </option>
            ))}
        </select>

        <select
          className="custom-select"
          onChange={this.onChangeItemList2}
          multiple
        >
          {itemlist2 &&
            itemlist2.map(item => (
              <option id={item.id} value={item.label}>
                {item.label}
              </option>
            ))}
        </select>
        <div className="col-md-2 ">
          <button
            onClick={this.handleadd}
            class="btn btn-primary btn-block w-25 margin-bottom"
          >
            <i class="fa fa-arrow-right" />
            Add
          </button>
          <button
            onClick={this.handleremove}
            class="btn btn-primary btn-block w-25"
          >
            <i class="fa fa-arrow-left" />
            Remove
          </button>
        </div>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<FieldForm />, rootElement);