findDOMNode在StrictMode中已被弃用。findDOMNode接收到了一个位于StrictMode内部的DraggableCore实例。

26

在严格模式下,Draggable包会引发错误:

警告:findDOMNode在StrictMode中已被弃用。 findDOMNode被传递给了StrictMode内部的DraggableCore实例。 相反,直接向要引用的元素添加一个ref。 在这里安全地了解更多关于使用refs的内容: https://reactjs.org/docs/strict-mode.html#warning-about-deprecated-finddomnode-usage

显然他们从未修复过这个问题https://github.com/STRML/react-draggable/issues/440,你有什么好的/优雅的解决方案吗?

1个回答

63

根据官方git存储库上的https://github.com/STRML/react-draggable/blob/v4.4.2/lib/DraggableCore.js#L159-L171

/* If running in React Strict mode, ReactDOM.findDOMNode() is deprecated.
* Unfortunately, in order for <Draggable> to work properly, we need raw access
* to the underlying DOM node. If you want to avoid the warning, pass a `nodeRef`
* as in this example:
*/

function MyComponent() {
    const nodeRef = React.useRef(null);
    return (
        <Draggable nodeRef={nodeRef}>
            <div ref={nodeRef}>Example Target</div>
        </Draggable>
    );
}

/*
* This can be used for arbitrarily nested components, so long as the ref ends up
* pointing to the actual child DOM node and not a custom component.
*/

它起作用了!


1
谢谢你关注自己的问题,这对我很有帮助! - Earle Poole
4
这应该是Draggable文档中的默认设置。 - Gifford N.
干得很干净,谢谢! - ZowWeb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接