在React中获取组件的高度 [英] Get the height of a Component in React

查看:1590
本文介绍了在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

I have 4 columns, none of whose height is fixed, and I need to find the height of these columns so that the height of the largest column can be set to the other three. How can I do this with React and not using the 'minHeight' css?

I am a newbie in React and the closest question I found here was ReactJS get rendered component height.

Also I found this link which says that this could be done by getting the DOMNode and using the Refs, but I'm with no success.

解决方案

You can just use the ref callback and access the DOMNode inside it.

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

Working example on jsfiddle: http://jsfiddle.net/vxub45kx/4/

Also look here: https://facebook.github.io/react/docs/more-about-refs.html

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

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