ReactJS - 获取元素的高度

新手上路,请多包涵

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

HTML

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

反应JS

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

原文由 faia20 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.3k
2 个回答

看到 这个 小提琴(实际上更新了你的)

您需要挂钩在 render 方法之后运行的 componentDidMount 。在那里,您可以获得元素的实际高度。

 var DivSize = React.createClass({
 getInitialState() {
 return { state: 0 };
 },

 componentDidMount() {
 const height = document.getElementById('container').clientHeight;
 this.setState({ height });
 },

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

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

 <script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>

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

原文由 Andreyco 发布,翻译遵循 CC BY-SA 4.0 许可协议

对于那些有兴趣使用 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>
  )
}

原文由 Mr. 14 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题