动画(淡入)img src(如果加载)反应#noJQuery

问题描述 投票:0回答:2

加载 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' }}
>
javascript html image reactjs src
2个回答
3
投票

图像上有一个

load
事件,该事件会在图像加载时触发,因此您可以用它来实现这一点

这是一个简单的小提琴


0
投票

使用 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} />

完整示例:https://codesandbox.io/s/6ykm7o4lzk

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.