简体   繁体   中英

How can I get the coordinates of a given element in react tsx

I am using React with Typescript and would like to know how to figure out the coordinates of a sub-component in a React class I wrote.

I already found this article: https://medium.com/@chung.andrew7/finding-the-absolute-positions-of-react-components-fda1c5bc9ab

And this: Get div's offsetTop positions in React

Here it is stated that this is usually done with getBoundingClientRect() , but I can't find any way how to do this with TypeScript, or what property or a ref this would be located on.

If I assign my component as _searchBarPreview: React.RefObject<{}>; by passing the following as "ref" prop on the element: ref={this._searchBarPreview} , I can't access the said function on that object at all.

What works is to assign the child component I want to get clients of an id and obtain the coordinates via:

document.getElementById('blablablablabla').getBoundingClientRect();

but there HAS to be a better way.

Any quick guidance?

Seem like that is the only way or you can use react-dom

class MyComponent extends React.Component {
  constructor(props) {
    super(props)
    this.myRef = React.createRef()
    const data = ReactDOM
      .findDOMNode(this.myRef)
      .getBoundingClientRect();
  }

  render() {
    return <div ref={this.myRef} />
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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