rap*_*lrk 3 javascript html5-canvas reactjs redux react-redux
我有一个图像 URL 列表。这些图像中的每一个有时会加载,有时会加载 404(意味着在某个时间加载的图像可能稍后会消失)。
let images = ['http://example.com/img1.jpg', ...];
Run Code Online (Sandbox Code Playgroud)
有没有办法请求这些图像,如果请求成功将它们保存在内存中,并在 React 中显示这些保存的图像?
componentDidMount() {
this.setState({ savedImages: images.map(saveImage)} );
}
render() {
return (
<div><image src={this.state.savedImages[0]}/></div>
);
}
Run Code Online (Sandbox Code Playgroud)
好的,让我将评论中的全部信息表示为完整的答案。
备注:这个问题实际上不是特定于 React 的,而是 vanilla JS。
这个想法是动态创建Image实例:
/* Somewhere inside the React class, I think */
preloadImages = () => {
let links = ["link1", "link2", "link3"]
/* the one react-specific thing is this.setState */
this.setState({ images: links.map((link, i) => {
// create an Image instance
var img = new Image()
// setting handler for load complete
img.onload = () => this.handleImageLoad(i)
// set the src attribute for it. After this line image loading will start
img.src = link
// return object with indicate of image loading statement
return {
url: link,
loaded: false
}
}) })
}
// nuff said, I suppose, this function is clear :)
handleImageLoad = index => {
var { images } = this.state
images[index].loaded = true
this.setState({ images })
}
Run Code Online (Sandbox Code Playgroud)
显然,现在您可以this.state.images在渲染中使用并仅渲染已加载的图像:)
| 归档时间: |
|
| 查看次数: |
5532 次 |
| 最近记录: |