ReactJS - 获取元素的高度

2022-08-30 01:41:16

在 React 渲染元素后,如何获取该元素的高度?

断续器

<div id="container">
<!-- This element's contents will be replaced with your component. -->
<p>
jnknwqkjnkj<br>
jhiwhiw (this is 36px height)
</p>
</div>

ReactJS

var DivSize = React.createClass({

  render: function() {
    let elHeight = document.getElementById('container').clientHeight
    return <div className="test">Size: <b>{elHeight}px</b> but it should be 18px after the render</div>;
  }
});

ReactDOM.render(
  <DivSize />,
  document.getElementById('container')
);

结果

Size: 36px but it should be 18px after the render

它计算渲染前的容器高度 (36px)。我想在渲染后获得高度。在这种情况下,正确的结果应该是18px。jsfiddle


答案 1

对于那些有兴趣使用 的人来说,这可能会帮助你入门。react hooks

import React, { useState, useEffect, useRef } from 'react'

export default () => {
  const [height, setHeight] = useState(0)
  const ref = useRef(null)

  useEffect(() => {
    setHeight(ref.current.clientHeight)
  })

  return (
    <div ref={ref}>
      {height}
    </div>
  )
}

答案 2

下面是使用 ref 的最新 ES6 示例。

请记住,我们必须使用 React 类组件,因为我们需要访问 Lifecycle 方法,因为我们只能在 DOM 中呈现元素后确定元素的高度。componentDidMount()

import React, {Component} from 'react'
import {render} from 'react-dom'

class DivSize extends Component {

  constructor(props) {
    super(props)

    this.state = {
      height: 0
    }
  }

  componentDidMount() {
    const height = this.divElement.clientHeight;
    this.setState({ height });
  }

  render() {
    return (
      <div 
        className="test"
        ref={ (divElement) => { this.divElement = divElement } }
      >
        Size: <b>{this.state.height}px</b> but it should be 18px after the render
      </div>
    )
  }
}

render(<DivSize />, document.querySelector('#container'))

您可以在此处找到运行示例:https://codepen.io/bassgang/pen/povzjKw