我正在尝试使用React JS获得父div的高度。
html结构如下:
<div ref="sectionSlider">
<div class="detailsOutterDiv">
<div class="swiper" style="width: 100%;">
<div class="detailsInnerDiv">
<div class="slide">
<img src="someURl" style="background-color: black;">
</div>
<div class="slide">
<img src="someURl" style="background-color: black;">
</div>
<div class="slide">
<img src="someURl" style="background-color: black;">
</div>
</div>
</div>
</div>
<div class="slider-thumbnails">
<div class="thumb">
<img src="someURl">
</div>
</div>
</div>
css-scss结构是这样的:
.detailsOutterDiv{
position: relative;
width: 100%;
overflow: hidden;
}
.detailsInnerDiv{
position: relative;
top: 0px;
left: 0px;
right: 0px;
width: 10000%;
transition: all 0.5s ease;
}
.slide{
display: inline-block;
margin-right: 15px;
}
.slide img{
width: 100%;
height: auto;
}
.slider-thumbnails{
width: 100%;
padding-top: $primary-margin-xs - 5;
text-align: center;
.thumb{
display: inline-block;
width: (100% / 12);
img{
width: 100%;
height: auto;
padding: 0 2px;
}
}
}
我正试图用ref="sectionSlider"
来获得div的高度。
我尝试在componentDidMount
中通过以下几种方式执行此操作:
componentDidMount(){
//First way
let top = this.refs["sectionSlider"].offsetHeight;
//Second way
let top = this.refs["sectionSlider"].clientHeight;
//Third way
let top = this.refs["sectionSlider"].getBoundingClientRect().height;
//Fourth way
let node = this.refs["sectionSlider"];
let nodeStyle = window.getComputedStyle(node);
let top = parseInt(nodeStyle.getPropertyValue('height').replace(/\D/g,''));
}
在每种情况下top
都是82,这是不正确的。
看起来像:
因此,div的高度为523。
知道怎么解决吗?
答案 0 :(得分:1)
如果问题是(根据您的猜测)未加载图像,您可以执行以下操作:
const Example = React.createClass({
getInitialState () {
return {
imagesLoaded: 0,
};
},
printClientHeight() {
console.log(this.wrapper.clientHeight)
},
updateLoadedImages() {
this.setState({ imagesLoaded: this.state.imagesLoaded + 1 })
if (this.state.imagesLoaded = 4) {
printClientHeight();
}
},
setWrapperRef(el) {
this.wrapper = el;
},
render() {
return (
<div ref={this.setWrapperRef}>
<div className="detailsOutterDiv">
<div className="swiper" style="width: 100%;">
<div className="detailsInnerDiv">
<div className="slide">
<img src="someURl" style="background-color: black;" onLoad={updateLoadedImages}/ >
</div>
<div className="slide">
<img src="someURl" style="background-color: black;" onLoad={updateLoadedImages}/>
</div>
<div className="slide">
<img src="someURl" style="background-color: black;" onLoad={updateLoadedImages}/>
</div>
</div>
</div>
</div>
<div className="slider-thumbnails">
<div className="thumb">
<img src="someURl" onLoad={updateLoadedImages}/>
</div>
</div>
</div>
);
}
});
显然你可以通过动态获取图像标签来清理这一点,但我认为你明白了......