簡體   English   中英

在React中獲取Component的高度

[英]Get the height of a Component in React

我有4列,其高度都沒有固定,我需要找到這些列的高度,以便最大列的高度可以設置為其他三列。 如何使用React並且不使用'minHeight'css?

我是React的新手,我在這里找到的最接近的問題是ReactJS獲得渲染的組件高度

另外我發現這個鏈接說這可以通過獲取DOMNode和使用Refs來完成,但我沒有成功。

您可以使用ref回調並訪問其中的DOMNode。

class Example extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            height: null
        };
        this.columns = ['hello', 
                        'this is a bit more text', 
                        'this is a bit more text ... and even more'];
    }

    render(){
        return <div ref={(node) => this.calcHeight(node)}>
                 {
                    this.columns.map((column) => {
                        return <div style={{height: this.state.height}}>{column}</div>
                    })
                 }
               </div>;
    }
    calcHeight(node) {
        if (node && !this.state.height) {
                this.setState({
                    height: node.offsetHeight
                });
        }
    }
}

React.render(<Example />, document.getElementById('container'));

關於jsfiddle的工作示例: http//jsfiddle.net/vxub45kx/4/

另請看這里: https//facebook.github.io/react/docs/more-about-refs.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM