在 React 中如何通过 ref 获取组件的位置?

How can I get component's position by ref in React?

我正在为我的应用程序使用 React 15.3.1。因此,我需要在 parent 中获取 Component x 和 y 位置。 child 呈现如下:

<Icon key={key} ref={(c) => this['icon' + key] = c}}/>;

这就是我尝试访问 Icon(基本上是 div)位置的方式:

let icon = this['icon' + this.state.currentIcon.id];
icon.getBoundingClientRect(); //Error: "getBoundingClientRect" is not a function

child 是正确的,我可以在调试器中看到它是 props。但是我看不到 getBoundingClientRectlefttop 等任何属性或任何其他位置属性。我需要做什么才能得到它们?

您的 ref 将引用 Icon,我猜这是一个 React 组件。在 getBoundingClientRect 方法可用之前,您需要解析实际的 React 元素(DOM 元素)。

您可以通过 ReactDOM.findDOMNode() 函数执行此操作。

let icon = this['icon' + this.state.currentIcon.id];
const domNode = ReactDOM.findDOMNode(icon);
domNode.getBoundingClientRect()