繁体   English   中英

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

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

我正在为我的应用程序使用React 15.3.1。 所以,我需要在它的父级中获得Component x和y位置。 孩子像这样呈现:

<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

孩子是对的,我可以在调试器中看到它的props 但我看不到任何属性,如getBoundingClientRectlefttop或任何其他位置属性。 得到它们我需要做什么?

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM