最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I get component's position by ref in React? - Stack Overflow

programmeradmin3浏览0评论

I'm using React 15.3.1 for my app. So, I need to get Component x and y positions in it's parent. The child is rendered like this:

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

And this is how I try to access Icon (which is basically a div) position:

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

The child is correct, I can see it's props in the debugger. But I cannot see any properties like getBoundingClientRect, left, top or any other position attributes. What I need to do to get them?

I'm using React 15.3.1 for my app. So, I need to get Component x and y positions in it's parent. The child is rendered like this:

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

And this is how I try to access Icon (which is basically a div) position:

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

The child is correct, I can see it's props in the debugger. But I cannot see any properties like getBoundingClientRect, left, top or any other position attributes. What I need to do to get them?

Share Improve this question asked Dec 15, 2016 at 13:14 JustLoginJustLogin 1,8905 gold badges30 silver badges50 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 17

Your ref will refer to Icon, which I'm guessing is a React Component. You need to resolve the actual React Element (DOM element) before the getBoundingClientRect method will be available.

You can do this through the ReactDOM.findDOMNode() function.

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

评论列表(0)

  1. 暂无评论