我需要用React获取图像的尺寸.我找到了一个名为
react-measure的库来计算React组件的测量值.它可以工作,但是当图像加载时我无法触发它.我需要在图像加载时触发它,这样我才能获得准确的尺寸,而不是0 x 157或类似的东西.
我尝试使用onLoad图像事件来检测图像何时加载,但我没有得到满意的结果.基本上我所做的是当图像加载(调用handleImageLoaded())时,将hasLoaded state属性更改为true.我知道hasLoaded已被改为true,因为它说的是:Image Loaded:true.
我注意到的是我只能计算已经缓存的图像的尺寸…
这是一个演示视频:cl.ly/250M2g3X1k21
是否有更好,更简洁的方法使用React正确检索尺寸?
这是代码:
import React,{Component} from 'react';
import Measure from '../src/react-measure';
class AtomicImage extends Component {
constructor() {
super();
this.state = {
hasLoaded: false,dimensions: {}
};
this.onMeasure = this.onMeasure.bind(this);
this.handleImageLoaded = this.handleImageLoaded.bind(this);
}
onMeasure(dimensions) {
this.setState({dimensions});
}
handleImageLoaded() {
this.setState({hasLoaded: true});
}
render() {
const {src} = this.props;
const {hasLoaded,dimensions} = this.state;
const {width,height} = dimensions;
return(
<div>
<p>Dimensions: {width} x {height}</p>
<p>Image Loaded: {hasLoaded ? 'true' : 'false'}</p>
<Measure onMeasure={this.onMeasure} shouldMeasure={hasLoaded === true}>
<div style={{display: 'inline-block'}}>
<img src={src} onLoad={this.handleImageLoaded}/>
</div>
</Measure>
</div>
);
}
}
export default AtomicImage;
这是父代码.它并不重要 – 只需将src传递给AtomicImage元素:
import React,{Component} from 'react';
import ReactDOM from 'react-dom';
import AtomicImage from './AtomicImage';
class App extends Component {
constructor() {
super();
this.state = {src: ''}
this.handleOnChange = this.handleOnChange.bind(this);
}
handleOnChange(e) {
this.setState({src: e.target.value});
}
render() {
const {src} = this.state;
return (
<div>
<div>
<input onChange={this.handleOnChange} type="text"/>
</div>
<AtomicImage src={src} />
</div>
)
}
}
ReactDOM.render(<App />,document.getElementById('app'));
解决方法
检索尺寸的方法
你可以通过js实现你的目标:通过offsetHeight,offsetWidth.
为了获得img的尺寸,img必须是可见的.你无法从缓存的img中获取维度.
例如:http://jsbin.com/hamene/4/edit?js,output
class AtomicImage extends Component {
constructor(props) {
super(props);
this.state = {dimensions: {}};
this.onImgLoad = this.onImgLoad.bind(this);
}
onImgLoad({target:img}) {
this.setState({dimensions:{height:img.offsetHeight,width:img.offsetWidth}});
}
render(){
const {src} = this.props;
const {width,height} = this.state.dimensions;
return (<div>
dimensions width{width},height{height}
<img onLoad={this.onImgLoad} src={src}/>
</div>
);
}
}