Javascript ReactJS - 获取元素的高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35153599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:19:55  来源:igfitidea点击:

ReactJS - Get Height of an element

javascriptreactjs

提问by faia20

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

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

HTML

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

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')
);

RESULT

结果

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

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. jsfiddle

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

采纳答案by Andreyco

See thisfiddle (actually updated your's)

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

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

您需要componentDidMount在 render 方法之后钩入哪个运行。在那里,您将获得元素的实际高度。

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>

回答by Paul Vincent Beigang

Following is an up to date ES6 example using a ref.

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

Remember that we have to use a React class componentsince we need to access the Lifecycle method componentDidMount()because we can only determine the height of an element after it is rendered in the DOM.

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

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'))

You can find the running example here: https://codepen.io/bassgang/pen/povzjKw

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

回答by Mr. 14

For those who are interested in using react hooks, this might help you get started.

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

回答by yoyodunno

You would also want to use refs on the element instead of using document.getElementById, it's just a slightly more robust thing.

您还希望在元素上使用 refs 而不是 using document.getElementById,它只是稍微更强大一些。

回答by qmn1711

I found useful npm package https://www.npmjs.com/package/element-resize-detector

我发现了有用的 npm 包https://www.npmjs.com/package/element-resize-detector

An optimized cross-browser resize listener for elements.

优化的跨浏览器调整元素大小的侦听器。

Can use it with React component or functional component(Specially useful for react hooks)

可以与 React 组件或功能组件一起使用(特别适用于 React 钩子)

回答by Gfast2

Here is another one if you need window resize event:

如果您需要窗口调整大小事件,这是另一个:

class DivSize extends React.Component {

  constructor(props) {
    super(props)

    this.state = {
      width: 0,
      height: 0
    }
    this.resizeHandler = this.resizeHandler.bind(this);
  }

  resizeHandler() {
    const width = this.divElement.clientWidth;
    const height = this.divElement.clientHeight;
    this.setState({ width, height });
  }

  componentDidMount() {
    this.resizeHandler();
    window.addEventListener('resize', this.resizeHandler);
  }

  componentWillUnmount(){
    window.removeEventListener('resize', this.resizeHandler);
  }

  render() {
    return (
      <div 
        className="test"
        ref={ (divElement) => { this.divElement = divElement } }
      >
        Size: widht: <b>{this.state.width}px</b>, height: <b>{this.state.height}px</b>
      </div>
    )
  }
}

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

code pen

密码笔

回答by TheDarkIn1978

An alternative solution, in case you want to retrieve the size of a React element synchronously without having to visibly render the element, you can use ReactDOMServerand DOMParser.

另一种解决方案是,如果您想同步检索 React 元素的大小而不必明显地呈现元素,则可以使用ReactDOMServerDOMParser

I use this function to get the height of a my list item renderer when using react-window(react-virtualized) instead of having to hardcode the required itemSizeprop for a FixedSizeList.

当使用react-window( react-virtualized) 而不是必须itemSizeFixedSizeList硬编码所需的道具时,我使用这个函数来获取我的列表项渲染器的高度。

utilities.js:

实用程序.js:

/**
 * @description Common and reusable functions 
 * 
 * @requires react-dom/server
 * 
 * @public
 * @module
 * 
 */
import ReactDOMServer from "react-dom/server";

/**
 * @description Retrieve the width and/or heigh of a React element without rendering and committing the element to the DOM.
 * 
 * @param {object} elementJSX - The target React element written in JSX.
 * @return {object} 
 * @public
 * @function
 * 
 * @example
 * 
 * const { width, height } = getReactElementSize( <div style={{ width: "20px", height: "40px" }} ...props /> );
 * console.log(`W: ${width}, H: ${height});  // W: 20, H: 40
 * 
 */
const getReactElementSize = (elementJSX) => {

    const elementString = ReactDOMServer.renderToStaticMarkup(elementJSX);
    const elementDocument = new DOMParser().parseFromString(elementString, "text/html");
    const elementNode = elementDocument.getRootNode().body.firstChild;

    const container = document.createElement("div");
    const containerStyle = {

        display: "block",
        position: "absolute",
        boxSizing: "border-box",
        margin: "0",
        padding: "0",
        visibility: "hidden"
    };

    Object.assign(container.style, containerStyle);

    container.appendChild(elementNode);
    document.body.appendChild(container);

    const width = container.clientWidth;
    const height = container.clientHeight;

    container.removeChild(elementNode);
    document.body.removeChild(container);

    return {

        width,
        height
    };
};

/**
 * Export module
 * 
 */
export {

    getReactElementSize
};

回答by whiteknight

Using with hooks :

与钩子一起使用:

This answer would be helpful if your content dimension changes after loading.

如果您的内容维度在加载后发生变化,这个答案会很有帮助。

onreadystatechange: Occurs when the load state of the data that belongs to an element or a HTML document changes. The onreadystatechange event is fired on a HTML document when the load state of the page's content has changed.

onreadystatechange:当属于元素或 HTML 文档的数据的加载状态发生变化时发生。当页面内容的加载状态发生变化时,onreadystatechange 事件会在 HTML 文档上触发。

import {useState, useEffect, useRef} from 'react';
const ref = useRef();
useEffect(() => {
    document.onreadystatechange = () => {
      console.log(ref.current.clientHeight);
    };
  }, []);

I was trying to work with a youtube video player embedding whose dimensions may change after loading.

我试图使用 youtube 视频播放器嵌入,其尺寸在加载后可能会改变。