反应拖放:Div拒绝拖动

时间:2019-10-16 20:55:56

标签: javascript css reactjs drag-and-drop drag

我试图构建一个具有拖放列表功能的React应用程序,而无需下载任何外部软件包。我发现a tutorial确实是这样做的

这是我的代码:

class App extends React.Component {
  state = {
    items: ["3", "2", "1", "4"]
  };

  onDragStart = (e, index) => {
    console.log("drag start!!!");
    this.draggedItem = this.state.items[index];
    e.dataTransfer.effectAllowed = "move";
    e.dataTransfer.setData("text/html", e.target.parentNode);
    e.dataTransfer.setDragImage(e.target.parentNode, 20, 20);
  };

  onDragOver = index => {
    const draggedOverItem = this.state.items[index];

    // if the item is dragged over itself, ignore
    if (this.draggedItem === draggedOverItem) {
      return;
    }

    // filter out the currently dragged item
    let items = this.state.items.filter(item => item !== this.draggedItem);

    // add the dragged item after the dragged over item
    items.splice(index, 0, this.draggedItem);

    this.setState({ items });
  };

  onDragEnd = () => {
    this.draggedIdx = null;
  };

  render() {
    return (
      <div className="App">
        <main>
          <h3>List of items</h3>
          <ul>
            {this.state.items.map((item, idx) => (
              <li key={item} onDragOver={() => this.onDragOver(idx)}>
                <div
                  className="drag"
                  draggable
                  onDragStart={e => this.onDragStart(e, idx)}
                  onDragEnd={this.onDragEnd}
                  style={{ cursor: "pointer" }}
                />
                <span className="content" style={{ cursor: "pointer" }}>
                  {item}
                </span>
              </li>
            ))}
          </ul>
        </main>
      </div>
    );
  }
}

我在控制台中没有任何错误。但是,列表中的项目拒绝被拖动。在我可以拖动项目的偶然机会上,我无法将其拖到想要去的地方,并且引入了一个奇怪的间隙/空间: enter image description here

这是我的密码和框:https://codesandbox.io/s/angry-dewdney-xzhsi

1 个答案:

答案 0 :(得分:2)

尝试更改渲染,以使可拖动的div用如下文本包裹跨度:

<div
 className="drag"
 draggable
 onDragStart={e => this.onDragStart(e, idx)}
 onDragEnd={this.onDragEnd}
 style={{ cursor: "pointer" }}
>
   <span className="content" style={{ cursor: "pointer" }}>
      {item}
   </span>
</div>

否则,您必须单击空白div,正如您指出的那样,这几乎是不可能的。通过这种方式,可拖动的div会包裹文本,因此,每当您单击文本时,都将单击div。