【问题标题】:animate (fadeIn) img src if loaded react #noJQuery动画(淡入)img src 如果加载反应#noJQuery
【发布时间】:2018-07-18 18:57:27
【问题描述】:

我遇到了 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' }}
>

thx 4 你的时间

【问题讨论】:

  • 不完全是淡入淡出效果,但您可以显示默认图像,直到实际图像实际加载。

标签: javascript html image reactjs src


【解决方案1】:

你有一个 load 事件在图像加载时触发,所以你可以用它来实现

这是一个简单的fiddle

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-07
      • 2011-10-18
      • 1970-01-01
      • 2011-05-12
      • 1970-01-01
      • 2011-10-26
      • 2021-04-09
      • 1970-01-01
      相关资源
      最近更新 更多