【问题标题】:Get element position in the DOM on React DnD drop?在 React DnD drop 上获取 DOM 中的元素位置?
【发布时间】:2017-11-26 19:30:17
【问题描述】:

我正在使用 React DnD 和 Redux(使用 Kea)来构建表单构建器。我的拖放部分工作得很好,当一个元素下降时我设法调度一个动作,然后我使用调度更改的状态渲染构建器。然而,为了以正确的顺序渲染元素,我(我想我)需要保存相对于它的兄弟元素的放置元素位置,但我无法弄清楚任何不是绝对疯狂的东西。我已经尝试过使用 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);
  });

如何实现我想要的?

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

【问题讨论】:

  • 我在这方面工作太久了,我很累,反正我也不太擅长用文字表达自己,所以如果有必要,请要求澄清,而不是盲目地投反对票和毁了我得到答案的机会:)
  • 我真的不明白你想要什么。告诉我你从什么数组开始,然后在删除后举例说明你希望它是什么样的。
  • 很难理解你想要什么 - 但我想是这样的:react-dnd.github.io/react-dnd/examples-sortable-simple.html

标签: javascript reactjs react-dnd


【解决方案1】:

我认为这里的关键是意识到Field 组件既可以是DragSource 也可以是DropTarget。然后,我们可以定义一组标准的 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
});

它只获取源对象和目标对象,以及发生的下降类型,然后将其转换为状态突变。

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

(bounds, position, source) => dropType

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

(bounds, position) => DropType.Inside

对于Field,您可以使用Simple Card Sort example 中的逻辑,其中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;
};

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

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

对于 React DnD,我们必须小心处理嵌套的放置目标,因为我们在 Workbench 中有 Fields:

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 应该包装被包装的组件。这样,我们就可以访问drop() 中正确的component 实例。

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

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

由于我们正在处理 DropTarget 中的下降,DragSource 只需要实现 beginDrag() 方法,它只会返回您想要混合到应用程序状态中的任何状态。

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

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

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

【讨论】:

  • 我的状态在一个版本中是一个对象,我决定使用数组,因为我发现它们更易于使用。我知道我可以使用 findDOMNode(),但这是我的问题:github.com/yannickcr/eslint-plugin-react/issues/678
  • 请查看以this comment 结尾的问题线程的完整交流。 drop() 调用时我们需要 DOM 节点,但 React DnD 只提供组件 props、监视器和 wrapped 组件。使用findDOMNode(),获取尺寸信息是微不足道的;没有它,没有那么多。
  • 还有一点需要注意,打开引用问题的用户@gaearon 也是 React DnD 的作者,并在 Sortable example 上被列为贡献者。
  • 我知道。该示例看起来像是来自Oct 15, 2015,而我引用的问题来自 2016 年 7 月 12 日。这在 JavaScript 世界中已经很长时间了,示例一直都过时了。我正在尝试构建一些可以长期工作的东西,如果他们在 19 中删除 findDOMNode,我不想被困在 React 18 中。
  • 所以我对如何实现现在可行但行不通的事情有了基本的了解。我的理解是应该使用 refs,但我缺乏如何将它们应用于我的案例的知识。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-17
  • 2011-11-26
  • 2015-04-22
  • 1970-01-01
  • 1970-01-01
  • 2023-02-16
  • 2014-08-19
相关资源
最近更新 更多