React获取组件外部元素的偏移量

时间:2019-01-10 05:53:47

标签: reactjs

我正在尝试获取React组件外部的元素的offsetTop,offsetLeft,offsetHeight等,并将值作为内联CSS传递给React组件。

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
  }

  const top = document.getElementById("div1").offsetTop;
  const left = document.getElementById("div1").offsetLeft;
  const bottom = document.getElementById("div1").offsetHeight;

  render() {
    return (
      <div 
         className="example"
         style={
           top: top,
           left: left,
           bottom: bottom,
         };
       ></div>
    );
  }
}

以上代码为undefinedtopleft偏移值提供了bottom

2 个答案:

答案 0 :(得分:1)

它们是未定义的,因为看起来您希望topleftbottom是类属性。

将它们放在您的构造函数中:

constructor(props) {
    super(props);
    this.top = document.getElementById("div1").offsetTop;
    this.left = document.getElementById("div1").offsetLeft;
    this.bottom = document.getElementById("div1").offsetHeight;
}

使用{this.top}{this.left}等访问它们。

答案 1 :(得分:1)

确认外部元素已安装

class MyComponent extends React.Component {
    state = { top: 0, left: 0, bottom: 0 }
    componentDidMount() {
        const top = document.getElementById( "div1" ).offsetTop;
        const left = document.getElementById( "div1" ).offsetLeft;
        const bottom = document.getElementById( "div1" ).offsetHeight;
        this.setState( { top, left, bottom } )
    }

    render() {
        const { top, left, bottom } = this.state;
        return (
            <div 
                className="example"
                style={
                   top: top,
                   left: left,
                   bottom: bottom,
                }
            ></div>
        );
    }
}