簡體   English   中英

反應:獲取元素的高度,並且this.ref具有空電流

[英]React: Get height of element, and this.ref has empty current

如何獲得組件內部div的高度? 我有以下代碼:

constructor(...) {
  ...
  this.detailsRef = React.createRef();
}

render() {
  return (
    <div>
      <span>A title</span>
      <div ref={this.detailsRef}>Some details</div>
    </div>
  );
 }

我讀過您可以通過執行以下操作獲取元素的高度:

this.detailsRef.current.clientHeight

要么

this.detailsRef.clientHeight

但是,這對我不起作用。 有人有什么建議嗎?

回答

好的,之所以不能從this.detailsRef.current.client獲取高度,是因為我的div附加了ref是由styled-components創建的div。 因此,當我將樣式化組件div更改為普通div時,它就起作用了。

像這樣:

class Test extends React.Component {
  constructor(props) {
    super(props);
    this.headerRef = React.createRef();
  }

  componentDidMount() {
    console.log(this.headerRef.current.clientHeight);
  }

  render() {
    return (
      <div>
        <h1 ref={this.headerRef}>Grab this element</h1>
      </div>
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM