加载 img src 时,我在 img 标签上显示灰色背景作为占位符。如果加载了 img src,那么我希望它淡入 img 中。是否可以制作像 img src 更改这样的动画?
<img
ref={ref => this.image = ref}
src={`someImgUrl`}
onError={() => this.image.setAttribute('src', 'someErrorImgUrl')}
style={{ width: '66px', height: '66px', backgroundColor: 'grey' }}
>
使用 React,你可以创建一个图像加载器组件,例如:
import React, { Component } from "react";
const _loaded = {};
class ImageLoader extends Component {
static defaultProps = {
className: "",
loadingClassName: "loading",
loadedClassName: "loaded"
};
constructor(props, context) {
super(props, context);
this.state = { loaded: _loaded[props.src] };
}
onLoad = () => {
console.log("LOADED");
_loaded[this.props.src] = true;
this.setState(() => ({ loaded: true }));
};
render() {
let { className, loadedClassName, loadingClassName, ...props } = this.props;
className = `${className} ${this.state.loaded
? loadedClassName
: loadingClassName}`;
return <img {...props} className={className} onLoad={this.onLoad} />;
}
}
export default ImageLoader;
稍后使用:
<ImageLoader src={src} />