使用Dragula拖放,React版本保存拖动项目的位置(react-dragula)

时间:2016-10-03 12:23:12

标签: javascript reactjs dragula react-dragula

我正在使用react-dragula(react-dragula)来拖放元素。掉落后如何保存物品位置。

  dragDecorator = () => {
            let options = { };
            Dragula([componentBackingInstance], options);
          }; 

     <div className="wrapper" ref={this.dragDecorator}>
       <div className="container col-md-4" id="0">
         <div className="panel panel-white" id="A1">
         </div>
         <div className="panel panel-white" id="A2">
        </div>
       </div>
       <div className="container col-md-4" id="0">
         <div className="panel panel-white" id="B1">
         </div>
         <div className="panel panel-white" id="B2">
        </div>
       </div>
    </div>

1 个答案:

答案 0 :(得分:1)

  dragDecorator = (componentBackingInstance) => {
    if (componentBackingInstance) {
      let options = {};

      const dragula = Dragula([componentBackingInstance], options);
      dragula.on('drop', (el, target, source, sibling) => {
        const newColumnIndex = parseInt(get(target, 'id'));
        const previousColumnIndex = parseInt(get(source, 'id'));
        const belowId = get(sibling, 'id');
        const itemId = get(el, 'id');

        let columns = this.state.columns;
        if (belowId === undefined) {
          const newItemIndex = columns[newColumnIndex].items.length;
          columns[previousColumnIndex].items.splice(columns[previousColumnIndex].items.indexOf(itemId), 1);
          columns[newColumnIndex].items.splice(newItemIndex, 0, itemId);
          this.setState({columns});
        }
        else {
          const newItemIndex = columns[newColumnIndex].items.indexOf(belowId);
          columns[previousColumnIndex].items.splice(columns[previousColumnIndex].items.indexOf(itemId), 1);
          columns[newColumnIndex].items.splice(newItemIndex, 0, itemId);
          this.setState({columns});
        }

        if (this.props.onDrag !== undefined) {
          this.props.onDrag(columns);
        }
      })
    }
  };

列将返回一个数组,其中包含每列中拖动项目的新位置,具体取决于其ID。