React中ref获取元素的宽度、高度,react中如何获得元素宽高

1.定义HTMLParagraphElement类型属性。

pvcDesDom:HTMLParagraphElement

2.componentDidMount中获取高度。

componentDidMount() {
        setTimeout(function () {
            this.setState({
                scrollHeight: this.pvcDesDom.scrollHeight
            })
        }.bind(this))
}

3.元素上追加ref属性。

<p className={'pvd-item-describe ' + (this.state.pvdDesShow ? '' : 'pvd-item-describe-hide')} ref={dom => { this.pvcDesDom = dom }}>data</p>

4.通过this.state.scrollHeight获取高度。

补充Dom的宽高和位置

// 尺寸:
clientWidth  |  clientHeight     元素的内尺寸(width + padding)如果有滚动条,是可视区域高度
scrollWidth  |  scrollHeight      元素滚动内容的总高度
offsetWidth  |  offsetHeight     元素的外尺寸  (width + padding + border)
// 位置:
offsetLeft  |  offsetTop     元素相对于已定位父元素(offsetParent)的偏移量
offsetParent元素是指元素最近的定位(relative,absolute)父元素,可递归上溯,如果没有,返回body元素
ele.getBoundingClientRect()   返回元素的大小及其相对可视区域的位置
如:ele.getBoundingClientRect().left   从视口左端到元素左端边框的距离(不包含外边距)
scrollLeft  |  scrollTop     是指元素滚动条位置,它们是可写的

点赞、关注加收藏,我们一起学前端?


版权声明:本文为Kindergarten_Sir原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。