React DnD:避免使用findDOMNode [英] React DnD: Avoid using findDOMNode

查看:478
本文介绍了React DnD:避免使用findDOMNode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I don't fully understand it but apparently it isn't recommended to use findDOMNode().

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

I'm trying to create drag and drop component but I'm not sure how I should access refs from the component variable. This is an example of what I currently have:

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

来源

修改

这可能是由于我的组件既是拖放源又是目标,因为我可以在此示例,而不是此示例.

It might be caused by my component being both the drag and drop source and target as I can get it to work in this example but not this one.

推荐答案

假设您使用的是es6类语法和最新版本的React(在撰写本文时为15),您可以像Dan一样附加一个回调引用在他的示例中,您分享了链接.来自文档 :

Assuming you're using es6 class syntax and the most recent version of React (15, at time of writing), you can attach a callback ref like Dan did in his example on the link you shared. From the docs:

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

When the ref attribute is used on an HTML element, the ref callback receives the underlying DOM element as its argument. For example, this code uses the ref callback to store a reference to a DOM node:

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

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

Then you can access the node just like we used to do with our old friends findDOMNode() or getDOMNode():

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

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

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

Because React DND does a bit of magic behind the scenes, we have to use their API to get at the decorated component. They provide getDecoratedComponentInstance() so you can get at the underlying component. Once you use that, you can get the component.node as expected:

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/

这篇关于React DnD:避免使用findDOMNode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆