ReactJS - 获取元素的高度 [英] ReactJS - Get Height of an element

查看:5438
本文介绍了ReactJS - 获取元素的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在React呈现该元素后获取元素的高度?

How can I get the Height of an element after React renders that element?

HTML

<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。

It's calculating the container height before the render (36px). I want to get the height after the render. The right result should be 18px in this case.

https:// jsfiddle。 net / 69z2wepo / 29800 /

推荐答案

参见这个小提琴(实际更新了你的)

See this fiddle (actually updated your's)

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

You need to hook into componentDidMount which is run after render method. There, you get actual height of element.

这篇关于ReactJS - 获取元素的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆