I am developping a React Application and trying to get the computed style 'scrollHeight' of a DOM Element.
I put this code in the componentDidMount:
componentDidMount() {
// let _this = this;
// window.onload = function(){
let imgFigureDOM = findDOMNode(_this.refs.imgFigure0),
imgW = imgFigureDOM.scrollWidth,
imgH = imgFigureDOM.scrollHeight;
// }
}
But, I can't get the correct value of scrollHeight only in the chrome browser.It seems that the chrome is not enough fast to render the DOMNode completely when the findDOMNode execute.
The value is correct when I use window.onload as above, but Shouldn't the DOMNode was completely loaded when the componentDidMount execute?
Thank you for your patient answer!
componentDidMount() is called when your React component is rendered. React has rendered an <img>
tag, that doesn't mean that the image is loaded.
Let's set up some basic definitions to distinguish rendered from loaded:
rendered: React has converted your virtual DOM elements (specified in the render method) into real DOM elements and attached them to the DOM.
loaded: Image data or other remote content has downloaded completely (or failed to download).
So just add the onLoad and onError event handlers to your React <img>
tag and away you go.
image-events
Short Example:
import React from 'react';
class ImageWithStatusText extends React.Component {
constructor(props) {
super(props);
this.state = { imageStatus: null };
}
handleImageLoaded(e){
this.setState({ imageStatus: 'loaded' });
console.log(e.target.scrollHeight);
}
handleImageErrored() {
this.setState({ imageStatus: 'failed to load' });
}
render() {
return (
<div>
<img
src={this.props.imageUrl}
onLoad={this.handleImageLoaded.bind(this)}
onError={this.handleImageErrored.bind(this)}
/>
{this.state.imageStatus}
</div>
);
}
}
export default ImageWithStatusText;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With