“clientHeight”不计一切元素 - 阵营
问题描述:
作出的DOM树是“clientHeight”不计一切元素 - 阵营
<Grid fluid ={true}>
<Row>
<NavigationBar
buttonClass='nav-button'
className='nav-bar'
/>
</Row>
<section id={sectionList[0]}>
<Row className='logo-row'>
<Col className='logo-wrap' xs={3} sm={3} md={2}>
{Logo}
</Col>
<Col xs={9} sm={9} md={10}>
{ProgrammerName}
</Col>
</Row>
{backgroundImg}
</section>
</Grid>
而我尝试使用下面的方法来检查<section>
的clientHeight:
const height = document.getElementById(sectionList[0]).clientHeight;
然而,看起来这个电话只会给出包含在<section>
中<Row>
的高度,忽略{backgroundImg}
表达式,它本身被调用来渲染另一个<Row>
组件。
<Row>
<FullRowImage src={this.props.src} alt={this.props.alt} />
<h2>
<span>
Some Text
</span>
</h2>
</Row>
什么可能是这个问题的原因,虽然离开了clientHeight
计数只有<section>
的一部分,其他的?
谢谢。
答
所以我终于明白了这一点。 由于<FullRowImage />
本身呈现<img>
,在加载<img>
之前调用clientHeight
,这将导致<img>
以及<FullRowImage>
的零高度。
在这种情况下,方法componentDidMount()
不够,因为安装的组件不能保证加载的图像。 在另一方面,onLoad
事件就会派上用场:
class FullRowImage extends React.Component {
constructor(props){
super(props);
this.state = {
loaded: false,
};
this.handleLoaded = this.handleLoaded.bind(this);
}
handleLoaded(){
console.log(document.getElementById('test').offsetHeight);
this.setState(
{loaded: true,}
);
}
render(){
return(
<img id='test'
onLoad={this.handleLoaded}
src={this.props.src}
alt= {this.props.alt} />
);
}
}
它加载后会打印出的<img>
高度。