如何使用react.js从列表拖放到树

时间:2018-11-27 06:22:20

标签: javascript reactjs drag-and-drop

我是React的新手,我正在尝试实现拖放屏幕。

我在jsFiddle上使用jQuery在线找到了一个示例。我在这里将代码复制为可运行的演示,因为没有代码示例就无法发布jsFiddle的链接。

任何人都可以为我指明如何在ReactJS中执行类似操作的正确方向吗?

var exData = [{
  id: "loc1",
  parent: "#",
  text: "Location 1"
}, {
  id: "loc2",
  parent: "#",
  text: "Location 2"
}, {
  id: "italy-1",
  parent: "loc2",
  text: "Italy",
  icon: "fa fa-flag"
}, {
  id: "poland-1",
  parent: "loc2",
  text: "Poland",
  icon: "fa fa-flag"
}];

function makeTreeItem(el) {
  return $("<a>", {
    id: $(el).attr("id") + "_anchor",
    class: "jstree-anchor",
    href: "#"
  });
}

$(function() {
  $('#tree').jstree({
    core: {
      check_callback: true,
      data: exData
    },
    types: {
      root: {
        icon: "fa fa-globe-o"
      }
    },
    plugins: ["dnd", "types"]
  });
  $('#tagList li').draggable({
    cursor: 'move',
    helper: 'clone',
    start: function(e, ui) {
      var item = $("<div>", {
        id: "jstree-dnd",
        class: "jstree-default"
      });
      $("<i>", {
        class: "jstree-icon jstree-er"
      }).appendTo(item);
      item.append($(this).text());
      var idRoot = $(this).attr("id").slice(0, -2);
      var newId = idRoot + "-" + ($("#tree [id|='" + idRoot + "'][class*='jstree-node']").length + 1);
      return $.vakata.dnd.start(e, {
        jstree: true,
        obj: makeTreeItem(this),
        nodes: [{
          id: newId,
          text: $(this).text(),
          icon: "fa fa-flag-o"
        }]
      }, item);
    }
  });
});
#tagList ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

#tagList ul li {
  background: #fff;
  border: 1px solid #ccc;
  width: auto;
  display: inline-block;
  padding: .125em .2em;
  margin: 3px 2px;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" rel="stylesheet"/>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>

<div class="ui-widget">
  <div class="ui-widget-header">
    Tags
  </div>
  <div id="tagList">
    <ul>
      <li data-tag="1" id="uk-1">United Kingdom</li>
      <li data-tag="2" id="france-1">France</li>
      <li data-tag="3" id="germany-1">Germany</li>
    </ul>
  </div>
</div>
<div class="ui-widget">
  <div class="ui-widget-header">
    Tree
  </div>
  <div id="tree">
  </div>
</div>

谢谢。

1 个答案:

答案 0 :(得分:1)

您提供的示例是用jQuery编写的。与其尝试在React中使jQuery UI的Draggable工作,不如使用React DnD。这是一个从根本上做同样事情的例子。

http://react-dnd.github.io/react-dnd/examples/nesting/drop-targets