以下是未呈现预加载器图像的原因:
> preloaderImage加载
>加载时,imageLoadHandler触发器并将src属性更改为主图像src(因此即使现在加载了preloaderImage也不会呈现)
>现在主图像加载
>加载时会渲染
你应该如何正确地做到:
>如果你写React应用程序,你应该这样做React方式:
>在构造函数方法中将图像设置为组件状态.你需要这样做是因为你要改变图像的渲染方式(在React中你通过改变组件的道具或状态实现渲染更改,在你的情况下它应该是状态).但请注意,您应该将列表中每个图像的src属性设置为preloaderImage(在下面的示例中我使用的是object destructuring语法).
constructor() {
super();
this.state = {
images: this.props.images.map(image => ({
...image,src: preloaderImage
}))
}
}
>现在在render方法中创建这样的图像列表(注意,这里不需要onLoad处理程序):
const listWork = this.state.images.map(image => (
));
>在componentWillMount方法中,开始使用vanilla JS动态加载主映像src(您可以阅读有关它的文章here).在加载它们时调用setState方法来更新图像src属性:
componentWillMount() {
this.state.images.forEach((image,index) => {
const {src} = this.props.images[index] // get image primary src
const primaryImage = new Image() // create an image object programmatically
primaryImage.onload = () => { // use arrow function here
console.log(`image #${index + 1} is loaded!`)
const images = [...this.state.images] // copy images array from state
images[index].src = src // adjust loaded image src
this.setState({
images
})
}
primaryImage.src = src // do it after you set onload handler
})
}
使用更改的图像数组调用setState后,React将使用正确的src路径自动重新渲染图像.
使用CSS更优雅的方式:
而不是< img />您可以使用< div />标记标签与background-image css属性.在那里你可以简单地设置你的后备(预加载)图像:
background-image: url('path/to/primary-image'),url('path/to/preload-image');
您可以使用style属性动态设置路径(在render方法中):
const listWork = this.props.images.map(image => {
const imageStyle = {
backgroundImage: `url(${image.src}),url(${preloaderImage});`
}
return (
)
})
只是不要忘记将高度和宽度设置为此< div />.
在React应用中,避免预加载器图片不显示的问题,应在构造函数中设置图片状态,并在componentWillMount中使用vanilla JS动态加载主图。当主图加载完成后,更新状态以触发重新渲染。另一种优雅的方法是使用CSS的background-image属性,设置预加载和主图作为背景。
893

被折叠的 条评论
为什么被折叠?



