React中ref获取元素的宽度、高度

1.定义HTMLParagraphElement类型属性。

pvcDesDom:HTMLParagraphElement
2.componentDidMount中获取高度。

componentDidMount() {
setTimeout(function () {
this.setState({
scrollHeight: this.pvcDesDom.scrollHeight
})
}.bind(this))
}
3.元素上追加ref属性。

补充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 是指元素滚动条位置,它们是可写的
如有转载请注明来源(洋葱先生:http://www.dreamload.cn/blog/?p=1034)

猜你喜欢

转载自blog.csdn.net/Kindergarten_Sir/article/details/108607389