Get div's offsetTop positions in React

前端 未结 6 848
暗喜
暗喜 2021-01-30 08:08

I am trying to implement a List view in React. What I am trying to achieve is that to store the list headers informations and register the components and register the scroll ev

相关标签:
6条回答
  • 2021-01-30 08:43

    A better solution with ref to avoid findDOMNode that is discouraged.

    ...
    onScroll() {
        let offsetTop  = this.instance.getBoundingClientRect().top;
    }
    ...
    render() {
    ...
    <Component ref={(el) => this.instance = el } />
    ...
    
    0 讨论(0)
  • 2021-01-30 08:47

    A quicker way if you are using React 16.3 and above is by creating a ref in the constructor, then attaching it to the component you wish to use with as shown below.

    ...
    constructor(props){
       ...
       //create a ref
       this.someRefName = React.createRef();
    

    }

    onScroll(){
    let offsetTop = this.someRefName.current.offsetTop;
    

    }

    render(){
    ...
    <Component ref={this.someRefName} />
    

    }

    0 讨论(0)
  • 2021-01-30 09:04
      import ReactDOM from 'react-dom';
      //...
      componentDidMount() {
        var n = ReactDOM.findDOMNode(this);
        console.log(n.offsetTop);
      }
    

    You can just grab the offsetTop from the Node.

    0 讨论(0)
  • 2021-01-30 09:06

    You may be encouraged to use the Element.getBoundingClientRect() method to get the top offset of your element. This method provides the full offset values (left, top, right, bottom, width, height) of your element in the viewport.

    Check the John Resig's post describing how helpful this method is.

    0 讨论(0)
  • 2021-01-30 09:07

    I do realize that the author asks question in relation to a class-based component, however I think it's worth mentioning that as of React 16.8.0 (February 6, 2019) you can take advantage of hooks in function-based components.

    Example code:

    import { useRef } from 'react'
    
    function Component() {
      const inputRef = useRef()
    
      return (
        <input ref={inputRef} />
        <div
          onScroll={() => {
            const { offsetTop } = inputRef.current
            ...
          }}
        >
      )
    }
    
    0 讨论(0)
  • 2021-01-30 09:09

    Eugene's answer uses the correct function to get the data, but for posterity I'd like to spell out exactly how to use it in React v0.14+ (according to this answer):

      import ReactDOM from 'react-dom';
      //...
      componentDidMount() {
        var rect = ReactDOM.findDOMNode(this)
          .getBoundingClientRect()
      }
    

    Is working for me perfectly, and I'm using the data to scroll to the top of the new component that just mounted.

    0 讨论(0)
提交回复
热议问题