Reactjs - 将列表项移动到另一个列表

时间:2017-06-29 23:41:44

标签: javascript reactjs

我正在慢慢得到诀窍(我认为)作出反应。我要做的是在一个组件中显示一个列表,然后使每个列表项(项目1,项目2等等)可单击,这样当它被单击时,它可以在两个{{之间来回移动1}}组件。我的内容如下,我想我的问题是在<ItemList />的第一个列表中设置状态。

handleEvent()

1 个答案:

答案 0 :(得分:2)

这是怎么做的..

所以,我将整个items数组传递给所有ItemLists,但是我也传递了状态,这只是一个包含该列表中包含项的ID的数组,请查看下面的逻辑并尝试理解,这是实际上很容易......

class SingleItem extends React.Component {
  render() {
    let data = this.props.data;

    return (
        <li onClick={this.props.onClick}>
            <div> {data.name} </div>
        </li>
    );
  }
}

class ItemList extends React.Component {
   render() {
     let itemArr = this.props.allItems;
     let myItems = this.props.items;
     let handleEvent = this.props.handleEvent;

     let listItems = itemArr.map((itemObj) => {
        if (!myItems.includes(itemObj.id)) return null;

        return <SingleItem 
          key={itemObj.id}
          data={itemObj}
          onClick={() => handleEvent(itemObj.id)}
        />;
     });

     return (
        <ul>
            {listItems}
        </ul>
     );
   }
}

class App extends React.Component {
constructor(props) {
    super(props);

    this.state = {
        boxOne: props.items.map(item => item.id), // init the boxes with itemIds
        boxTwo: []
    };

    this.handleEvent = this.handleEvent.bind(this);
}

handleEvent(itemId) {
    const isInBoxOne = this.state.boxOne.includes(itemId);

    // Heres the magic, if the item is in the first Box, filter it out,
    // and put into the second, otherwise the other way around..
    this.setState({
        boxOne: isInBoxOne
          ? this.state.boxOne.filter(i => i !== itemId)
          : [ ...this.state.boxOne, itemId ]
        boxTwo: isInBoxOne
          ? [ ...this.state.boxTwo, itemId ]
          : this.state.boxTwo.filter(i => i !== itemId)
    });
}
render() {
    return (
        <div>
            <ItemList handleEvent={this.handleEvent} items={this.state.boxOne} allItems={this.props.items} />
            <ItemList handleEvent={this.handleEvent} items={this.state.boxTwo} allItems={this.props.items} />
        </div>
    );
  }
};

var items = [
  {name: "Item 1", id: 1},
  {name: "Item 2", id: 2},
  {name: "Item 3", id: 3},
  {name: "Item 4", id: 4},
]

ReactDOM.render(
  // Pass the initial items to your App
  <App items={items} />,
  document.getElementById('root')
);