我有一个代表用户头像的组件,它从我的API加载图像.我希望它在加载头像时显示默认头像(不是另一个图像).
constructor() {
super();
this.state = {
loaded: false,
};
}
render() {
if (!this.props.uri || !this.state.loaded) {
return (
<DefaultAvatar />
);
}
return <Image onLoad={this.onLoad.bind(this)} uri={this.props.uri} />;
}
onLoad() {
this.setState({loaded: true});
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,使用当前代码,Image
永远不会呈现,因此状态永远不会改变.我无法找到满足React原则和我的要求的解决方案(在显示图像之前没有加载图像的ghost组件).
class LazyImage extends React.Component{
constructor () {
super(this.props)
this.state = {loaded: false}
}
handleLoad () {
this.setState({loaded:true})
}
componentDidMount () {
this.img = new Image()
this.img.onload = this.handleLoad.bind(this)
this.img.src = this.props.src
}
render () {
return this.state.loaded?<img src={this.props.src}/>:<div>Loading...</div>
}
}
Run Code Online (Sandbox Code Playgroud)
您创建一个本机Image
元素并等待它加载.然后用反应渲染图像.浏览器是智能的,这次从缓存中取出它.即时渲染!
有关演示,请参见http://jsfiddle.net/4hq3y4ra/3/.
归档时间: |
|
查看次数: |
4279 次 |
最近记录: |