我正在使用Reactjs,我想获得一个img元素的高度,我想保持img的比例,所以我要像这样在css中设置图像。
.img {
position: fixed;
z-index: 999;
width: 30%;
height: auto;
left: 5%;
object-fit: fill;
}
请注意,此处的高度为“自动”。
现在我只是想像这样在componentDidMount()中获取它的渲染高度:
componentDidMount() {
const height = document.getElementById('ImgID').clientHeight;
const width = document.getElementById('ImgID').clientWidth;
console.log(height, width)
}
我检查只是在控制台中打印结果,但日志显示高度为0,宽度为252(显式宽度)。
事实是图像出现在屏幕上,并且高度在视觉上不是0。然后我尝试通过打印手动检查属性'clientHeight':
console.log(document.getElementById('ImgID').attributes)
通过展开'style> ownerElement> clientHeight',我看到客户端的高度为49,不为零,但是我无法获得正确的值:/。
我正在寻找一种解决方案来提高这种情况的高度,可以使用Javascript / css或同时使用这两种方法来完成。我试图避免使用JQuery,因为React使用的是虚拟DOM,而不是浏览器DOM。
-------------------更新--------------------
这是@ııı的答案所建议的getBoundingClientRect()的内容
答案 0 :(得分:2)
这实际上是因为执行componentDidMount()
时尚未加载图像。 <img>
在DOM中,但是height
在图像加载之前是未知的(除非从CSS显式设置)。解决方案是在onLoad
中查询高度。请参见下面的测试:
class Test extends React.Component {
componentDidMount() {
//console.log(this.refs.img.getBoundingClientRect().height);
console.log('componentDidMount', this.refs.img.clientHeight);
}
imageLoaded = () => {
console.log('imageLoaded', this.refs.img.clientHeight);
}
render() {
return <img src="http://placekitten.com/200/200"
ref="img"
onLoad={this.imageLoaded}
/>;
}
}
ReactDOM.render(<Test />, document.getElementById('app'));
<script src="http://unpkg.com/react/umd/react.production.min.js"></script>
<script src="http://unpkg.com/react-dom/umd/react-dom.production.min.js"></script>
<div id="app"></div>