在React DnD下降中获取DOM中的元素位置?

时间:2017-11-26 19:30:18

标签: javascript reactjs react-dnd

我正在使用React DnD和Redux(使用Kea)来构建formbuilder。我是拖拉机drop部分工作正常,我已经设法在元素丢失时调度一个动作,然后我使用调度更改的状态渲染构建器。但是,为了以正确的顺序渲染元素,我(我想)我需要保存相对于它的兄弟姐妹的丢弃元素位置,但我无法弄清楚任何不是绝对疯狂的东西。我已尝试使用refs并使用唯一ID查询DOM(我知道我不应该),但这两种方法都非常糟糕,甚至无法工作。

以下是我的应用结构的简化表示:

@DragDropContext(HTML5Backend)
@connect({ /* redux things */ })
<Builder>
  <Workbench tree={this.props.tree} />
  <Sidebar fields={this.props.field}/>
</Builder>

工作台:

const boxTarget = {
  drop(props, monitor, component) {
    const item = monitor.getItem()
    console.log(component, item.unique, component[item.unique]); // last one is undefined
    window.component = component; // doing it manually works, so the element just isn't in the DOM yet

    return {
      key: 'workbench',
    }
  },
}

@DropTarget(ItemTypes.FIELD, boxTarget, (connect, monitor) => ({
  connectDropTarget: connect.dropTarget(),
  isOver: monitor.isOver(),
  canDrop: monitor.canDrop(),
}))
export default class Workbench extends Component {
  render() {
    const { tree } = this.props;
    const { canDrop, isOver, connectDropTarget } = this.props

    return connectDropTarget(
      <div className={this.props.className}>
        {tree.map((field, index) => {
          const { key, attributes, parent, unique } = field;
          if (parent === 'workbench') { // To render only root level nodes. I know how to render the children recursively, but to keep things simple...
            return (
              <Field
                unique={unique}
                key={key}
                _key={key}
                parent={this} // I'm passing the parent because the refs are useless in the Field instance (?) I don't know if this is a bad idea or not
              />
            );
          }

          return null;
        }).filter(Boolean)}
      </div>,
    )


    // ...

字段:

const boxSource = {
  beginDrag(props) {
    return {
      key: props._key,
      unique: props.unique || shortid.generate(),
      attributes: props.attributes,
    }
  },

  endDrag(props, monitor) {
    const item = monitor.getItem()
    const dropResult = monitor.getDropResult()

    console.log(dropResult);

    if (dropResult) {
      props.actions.onDrop({
        item,
        dropResult,
      });
    }
  },
}

@connect({ /* redux stuff */ })
@DragSource(ItemTypes.FIELD, boxSource, (connect, monitor) => ({
  connectDragSource: connect.dragSource(),
  isDragging: monitor.isDragging(),
}))
export default class Field extends Component {  
  render() {
    const { TagName, title, attributes, parent } = this.props
    const { isDragging, connectDragSource } = this.props
    const opacity = isDragging ? 0.4 : 1

    return connectDragSource(
      <div
        className={classes.frame}
        style={{opacity}}
        data-unique={this.props.unique || false}
        ref={(x) => parent[this.props.unique || this.props.key] = x} // If I save the ref to this instance, how do I access it in the drop function that works in context to boxTarget & Workbench? 
      >
        <header className={classes.header}>
          <span className={classes.headerName}>{title}</span>
        </header>
      <div className={classes.wrapper}>
        <TagName {...attributes} />
      </div>
    </div>
    )
  }
}

补充工具栏不太相关。

我的状态是一个平面数组,由我可以用来渲染字段的对象组成,因此我根据DOM中的元素位置对其进行重新排序。

[
  {
    key: 'field_type1',
    parent: 'workbench',
    children: ['DAWPNC'], // If there's more children, "mutate" this according to the DOM
    unique: 'AWJOPD',
    attributes: {},
  },
  {
    key: 'field_type2',
    parent: 'AWJOPD',
    children: false,
    unique: 'DAWPNC',
    attributes: {},
  },
]

这个问题的相关部分围绕着

const boxTarget = {
  drop(props, monitor, component) {
    const item = monitor.getItem()
    console.log(component, item.unique, component[item.unique]); // last one is undefined
    window.component = component; // doing it manually works, so the element just isn't in the DOM yet

    return {
      key: 'workbench',
    }
  },
}

我想我只是以某种方式得到元素的引用,但它似乎并不存在于DOM中。如果我试图破解ReactDOM,那就是同样的事情:

 // still inside the drop function, "works" with the timeout, doesn't without, but this is a bad idea
 setTimeout(() => {
    const domNode = ReactDOM.findDOMNode(component);
    const itemEl = domNode.querySelector(`[data-unique="${item.unique}"]`);
    const parentEl = itemEl.parentNode;

    const index = Array.from(parentEl.children).findIndex(x => x.getAttribute('data-unique') === item.unique);

    console.log(domNode, itemEl, index);
  });

我如何实现我想要的目标?

对于我使用分号不一致的道歉,我不知道我想从他们那里得到什么。 我恨他们。

1 个答案:

答案 0 :(得分:4)

我认为这里的关键是认识到Field组件可以是DragSourceDropTarget。然后,我们可以定义一组标准的drop类型,这些类型会影响状态的变异。

const DropType = {
  After: 'DROP_AFTER',
  Before: 'DROP_BEFORE',
  Inside: 'DROP_INSIDE'
};

AfterBefore将允许重新排序字段,而Inside将允许嵌套字段(或放入工作台)。

现在,处理任何丢弃的动作创建者将是:

const drop = (source, target, dropType) => ({
  type: actions.DROP,
  source,
  target,
  dropType
});

它只需要源和目标对象以及发生的丢弃类型,然后将其转换为状态变异。

drop类型实际上只是目标边界,放置位置和(可选)拖动源的函数,所有这些都在特定DropTarget类型的上下文中:

(bounds, position, source) => dropType

应为每种支持的DropTarget类型定义此功能。这将允许每个DropTarget支持一组不同的drop类型。例如,Workbench只知道如何丢弃内部的东西,而不是之前或之后,因此工作台的实现可能如下所示:

(bounds, position) => DropType.Inside

对于Field,您可以使用Simple Card Sort example中的逻辑,其中DropTarget的上半部分转换为Before下降,而下半部分转换为一个After drop:

(bounds, position) => {
  const middleY = (bounds.bottom - bounds.top) / 2;
  const relativeY = position.y - bounds.top;
  return relativeY < middleY ? DropType.Before : DropType.After;
};

这种方法也意味着每个DropTarget都可以以相同的方式处理drop()规范方法:

  • 获取放置目标的DOM元素的边界
  • 获得放弃位置
  • 从边界,位置和来源
  • 计算掉落类型
  • 如果发生任何丢弃类型,请处理放置操作

使用React DnD,我们必须小心处理嵌套的放置目标,因为Field中有Workbench个:

const configureDrop = getDropType => (props, monitor, component) => {
  // a nested element handled the drop already
  if (monitor.didDrop())
    return;

  // requires that the component attach the ref to a node property
  const { node } = component;
  if (!node) return;

  const bounds = node.getBoundingClientRect();
  const position = monitor.getClientOffset();
  const source = monitor.getItem();

  const dropType = getDropType(bounds, position, source);

  if (!dropType)
    return;

  const { onDrop, ...target } = props;
  onDrop(source, target, dropType);

  // won't be used, but need to declare that the drop was handled
  return { dropped: true };
};

Component类最终会看起来像这样:

@connect(...)
@DragSource(ItemTypes.FIELD, { 
  beginDrag: ({ unique, parent, attributes }) => ({ unique, parent, attributes })
}, dragCollect)
// IMPORTANT: DropTarget has to be applied first so we aren't receiving
// the wrapped DragSource component in the drop() component argument
@DropTarget(ItemTypes.FIELD, { 
  drop: configureDrop(getFieldDropType)
  canDrop: ({ parent }) => parent // don't drop if it isn't on the Workbench
}, dropCollect)
class Field extends React.Component {
  render() { 
    return (
      // ref prop used to provide access to the underlying DOM node in drop()
      <div ref={ref => this.node = ref}>
        // field stuff
      </div>
    );
}

要注意事项:

注意装饰者的顺序。 DropTarget应该包装组件,然后DragSource应该包装组件。这样,我们就可以访问component内的正确drop()实例。

放置目标的根节点需要是本机元素节点,而不是自定义组件节点。

将使用DropTarget利用configureDrop()修饰的任何组件都要求组件将其根节点的DOM ref设置为node属性。

由于我们正在处理DropTarget中的丢弃,因此DragSource只需要实现beginDrag()方法,该方法只返回您希望混合到应用程序状态的任何状态。

最后要做的是处理reducer中的每个drop类型。需要记住的重要一点是,每次移动时,都需要从当前父级移除源(如果适用),然后插入新父级。每个操作都可以改变最多三个元素的状态,源的现有父级(清理其children),源(分配其parent引用)和目标&# 39; s {父母或目标Inside下降(添加 到children)。

您还可以考虑将您的状态设置为对象而不是数组,这在实现reducer时可能更容易使用。

{
  AWJOPD: { ... },
  DAWPNC: { ... },
  workbench: {
    key: 'workbench',
    parent: null,
    children: [ 'DAWPNC' ]
  }
}