简体   繁体   English

获取 React 组件中子元素的高度

[英]Getting height of children elements in a React component

Inside a React component, I want to be able to calculate the combined height of each of my child containers, in this case, the three h3 elements, so that I can calculate the exact height of my parent div when animating the transition of its height.在 React 组件中,我希望能够计算每个子容器的组合高度,在本例中为三个 h3 元素,以便在为其高度的过渡设置动画时计算父 div 的确切高度. I have seen examples of this with basic js as well as using component mounting methods, but how do I get the height of these elements using just JavaScript?我已经看到使用基本 js 以及使用组件安装方法的示例,但是如何仅使用 JavaScript 获取这些元素的高度?

 class Div extends React.Component { render() { return ( <div> <h3>Description One</h3> <h3>Description Two</h3> <h3>Description Three</h3> </div> ); } } ReactDOM.render(<Div />, app);
 div { background-color: pink; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="app"></div>

In React, to manipulate the DOM, you'll want to use Refs: React Docs - Adding a Ref to a DOM element .在 React 中,要操作 DOM,您需要使用 Refs: React Docs - Add a Ref to a DOM element

In your example, for your <h3> elements, you'd do something like this:在您的示例中,对于<h3>元素,您可以执行以下操作:

    <h3 ref={(elem) => this.Line1 = elem}>Description One</h3>
    <h3 ref={(elem) => this.Line2 = elem}>Description Two</h3>
    <h3 ref={(elem) => this.Line3 = elem}>Description Three</h3>

Once you have a Ref to an element, you can use methods & properties of any DOM element on it.一旦你有了一个元素的 Ref,你就可以在它上面使用任何 DOM 元素的方法和属性。 For instance, to get its height, you can use Element.clientHeight :例如,要获取其高度,您可以使用Element.clientHeight

calcHeight() {
  return this.Line1.clientHeight + this.Line2.clientHeight + this.Line3.clientHeight;
}

Working JSFiddle工作 JSFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM