小编典典

React DnD:避免使用findDOMNode

reactjs

我不完全了解它,但显然不建议使用findDOMNode()

我正在尝试创建拖放组件,但不确定如何从组件变量访问引用。这是我目前拥有的一个例子:

const cardTarget = {
    hover(props, monitor, component) {
        ...
        // Determine rectangle on screen
        const hoverBoundingRect = findDOMNode(component).getBoundingClientRect();
        ...
    }
}

资源

编辑

这可能是由我的部件是拖放源都和目标,我可以得到它的工作造成的这个例子,但不是这一个


阅读 355

收藏
2020-07-22

共1个答案

小编典典

假设您使用的是es6类语法和最新版本的React(在撰写本文时为15),则可以像Dan在其示例中所做的那样,在共享链接上附加一个回调引用。从文档

在HTML元素上使用ref属性时,ref回调将接收基础DOM元素作为其参数。例如,此代码使用ref回调存储对DOM节点的引用:

<h3
    className="widget"
    onMouseOver={ this.handleHover.bind( this ) }
    ref={node => this.node = node}
>

然后,您可以访问节点,就像我们以前与老朋友findDOMNode()或那样getDOMNode()

handleHover() {
  const rect = this.node.getBoundingClientRect(); // Your DOM node
  this.setState({ rect });
}

实际使用中:https
//jsfiddle.net/ftub8ro6/

编辑:

因为React
DND在幕后做了一些魔术,所以我们必须使用它们的API来获得装饰组件。它们提供了功能,getDecoratedComponentInstance()因此您可以使用基础组件。一旦使用它,您将获得component.node预期的效果:

hover(props, monitor, component) {
    const dragIndex = monitor.getItem().index;
    const hoverIndex = props.index;
    const rawComponent = component.getDecoratedComponentInstance();
    console.log( rawComponent.node.getBoundingClientRect() );
    ...

它在起作用:

https://jsfiddle.net/h4w4btz9/2/

2020-07-22