reactjs – 使用onLoad方法在React中加载图像?
我的目标是让我的图库图像在加载时呈现.
在线查看,我了解了onLoad方法. 这是我试图利用的,这个想法是preloader.gif将呈现,直到图像被加载,并简单地用加载的图像替换图像src. 就像现在(下图)一样,如果我没有使用onLoad方法,图像似乎加载的方式与通常情况相同,因此在图像加载之前有一个时刻根本没有渲染图像. 我究竟做错了什么? 我已经删除了代码以使问题更容易阅读. import React from 'react'; import ReactDOM from 'react-dom'; import preloaderImage from '../../../img/site/preloader.gif'; class WorksPage extends React.Component { constructor(){ super(); } imageLoadHandler(image,e) { e.target.src = image; } render() { const listWork = this.props.array.map((item,index)=> { return( <li key={item.id}> <div> <img src={preloaderImage} onLoad={this.imageLoadHandler.bind(this,item.image)}/> </div> </li> ) }); return( <li> <div> <ul> {listWork} </ul> </div> </li> ) } } module.exports = WorksPage;
以下是未呈现预加载器图像的原因:
> preloaderImage加载 你应该如何正确地做到: >如果你写React应用程序,你应该这样做React方式: >在构造函数方法中将图像设置为组件状态.你需要这样做是因为你要改变图像的渲染方式(在React中你通过改变组件的道具或状态实现渲染更改,在你的情况下它应该是状态).但请注意,您应该将列表中每个图像的src属性设置为preloaderImage(在下面的示例中我使用的是 constructor() { super(); this.state = { images: this.props.images.map(image => ({ ...image,src: preloaderImage })) } } >现在在render方法中创建这样的图像列表(注意,这里不需要onLoad处理程序): const listWork = this.state.images.map(image => ( <li key={image.id}> <div> <img src={image.src} /> </div> </li> )); >在componentWillMount方法中,开始使用vanilla JS动态加载主映像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 ( <li key={image.id}> <div> <div style={imageStyle} /> </div> </li> ) }) 只是不要忘记将高度和宽度设置为此< div />. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |