反应拖放-如果在onDragOver中调用setState,则不会调用onDrop

时间:2019-05-20 12:27:54

标签: reactjs drag-and-drop

我正在尝试实现拖放操作,如果我在onDragOver处理程序中调用setState(以便能够基于拖动状态进行某些样式设置),则不会在第二次放置时调用onDrop。如果我删除对setState的调用,它将正常工作。让我感到困惑的是它第一次起作用。我希望,如果它不起作用,那就根本不起作用。

注意:我正在对样式化的组件进行反应。

我有一个基于类的组件,如下所示:

  state = {
    status: STATUS.NOT_DRAGGING,
  };

  onDragOver = (e) => {
    e.preventDefault();
    // this line is causing all the trouble
    // this.setState(() => ({ status: STATUS.DRAGGING }));
  };

  onDrop = (e, rowId) => {
    // get the item being dragged using dto
    const id = e.dataTransfer.getData('id');
    const name = e.dataTransfer.getData('name');

    // clear out the data transfer array
    e.dataTransfer.clearData();

    if (id === null || id === 'undefined') return;

    const node = { id, name };
    const settings = this.props.getPlotContainer(rowId).settings;

    // add node to plot
    this.props.addNodeToPlot(rowId, node, settings);

    this.setState({ status: STATUS.DROPPED });
  };

和我的可投放div:

      <MainContainer
        status={this.state.status}
        className="droppable"
        onDragOver={e => this.onDragOver(e)}
        onDrop={e => this.onDrop(e, rowId)}
      >
        {(plot && plot.nodes.length === 0) && <EmptyPlot status={this.state.status}>{message}</EmptyPlot>}
        {(plot && plot.nodes.length > 0) && this.renderPlotSettings(plot, rowId)}
        {(plot && plot.nodes.length > 0) && this.renderPlot(plot)}
        {(plot && plot.nodes.length > 0) && this.renderSeriesSettings(plot, rowId)}
      </MainContainer>

任何建议或提示都将不胜感激!

1 个答案:

答案 0 :(得分:0)

如果有人遇到此问题,我会提供解决方案。

我能想到的最好的解决方法是将拖动状态从可放置元素的onDragOver设置为可拖动元素的onDragStart和onDragEnd事件。由于这些元素位于不同的组件中,因此我将状态从组件移到了redux。

请注意,在诸如onDrag,onDragOver等事件在未知时间段内“连续”发生的事件时,我还将避免设置状态或触发动作。

希望这可以帮助其他人。

相关问题