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

Chr*_*ian 7 javascript reactjs react-dnd

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

这是我的app结构的简化表示:

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

工作台:

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>,
    )


    // ...
Run Code Online (Sandbox Code Playgroud)

领域:

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>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

补充工具栏不是很相关.

我的状态是一个平面数组,由我可以用来渲染字段的对象组成,所以我根据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: {},
  },
]
Run Code Online (Sandbox Code Playgroud)

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

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',
    }
  },
}
Run Code Online (Sandbox Code Playgroud)

我想我会以某种方式获得对元素的引用,但它似乎并不存在于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);
  });
Run Code Online (Sandbox Code Playgroud)

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

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

Rob*_*ley 5

我认为这里的关键是意识到Field组件可以是 aDragSource和 a DropTarget。然后,我们可以定义一组标准的丢弃类型,这些类型会影响状态的变异方式。

const DropType = {
  After: 'DROP_AFTER',
  Before: 'DROP_BEFORE',
  Inside: 'DROP_INSIDE'
};
Run Code Online (Sandbox Code Playgroud)

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

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

const drop = (source, target, dropType) => ({
  type: actions.DROP,
  source,
  target,
  dropType
});
Run Code Online (Sandbox Code Playgroud)

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

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

(bounds, position, source) => dropType
Run Code Online (Sandbox Code Playgroud)

应该为每种DropTarget支持的类型定义这个函数。这将允许每个DropTarget都支持一组不同的丢弃类型。例如,Workbenchonly 知道如何在其内部放置一些东西,而不是之前或之后,因此工作台的实现可能如下所示:

(bounds, position) => DropType.Inside
Run Code Online (Sandbox Code Playgroud)

对于 a Field,您可以使用Simple Card Sort 示例中的逻辑,其中上半部分DropTarget转换为Before放置,而下半部分转换为After放置:

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

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

  • 获取放置目标的 DOM 元素的边界
  • 获取掉落位置
  • 根据边界、位置和源计算放置类型
  • 如果发生任何放置类型,则处理放置操作

使用 React DnD,我们必须小心适当地处理嵌套放置目标,因为我们Field在 a 中有s 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 };
};
Run Code Online (Sandbox Code Playgroud)

这个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>
    );
}
Run Code Online (Sandbox Code Playgroud)

需要注意的几点:

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

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

将与装饰任何组件DropTarget利用configureDrop()将要求组件设置它的根节点的DOMrefnode属性。

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

最后要做的是处理您的减速器中的每个 drop 类型。重要的是要记住,每次移动某些东西时,都需要从其当前父级(如果适用)中删除源,然后其插入到新父级中。每个动作最多可以改变三个元素的状态,源的现有父级(清理其children),源(分配其parent引用),以及目标的父级或目标Inside(添加到其children)。

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

{
  AWJOPD: { ... },
  DAWPNC: { ... },
  workbench: {
    key: 'workbench',
    parent: null,
    children: [ 'DAWPNC' ]
  }
}
Run Code Online (Sandbox Code Playgroud)