img标记滞后一点,显示旧页面图像一两秒钟,然后显示新图像中的反应

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

页面上有一个上一个和一个下一个按钮,使我们可以遍历页面,在包含图像的卡片行中显示数据。第一次单击上一个按钮的下一个时,文本字段立即显示,但是img标签滞后了一点,显示了旧页面图像一两秒钟,然后显示了新图像。

知道如何防止这种情况吗?或至少使第一张图像立即消失?

reactjs image lag
1个回答
0
投票

从您提供的信息来看,很难共享解决方案,而我们甚至都看不到它。我可以建议您在映像中添加一个加载器,以便为您带来更好的用户体验。尝试以下操作:

 class LoadableImage extends Component {
  state = {
    isLoaded: false,
  };

  render() {
    let { path, alt, onLoad, ...rest } = this.props;
    return (
      <div className='position-relative h-100'>
        <img
          className='img-fluid p-3'
          src={ path }
          alt={ alt }
          { ...rest }
          onLoad={ this.handleImageLoad }
        />
        { !this.state.isLoaded && (
          <div className="loader-container">
            <span className="loader text-center">
              <div> Custom loader text or animation </div>
            </span>
          </div>
        )
        }
      </div>
    );
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    if (prevProps.path !== this.props.path) {
      this.setState({ isLoaded: false });
    }
  }

  /**
   * Handles the load of the image and executes any overriden onLoad functions if available.
   * @param {Event} e
   */
  handleImageLoad = (e) => {
    if (this.props.onLoad) {
      this.props.onLoad(e);
    }
    this.setState({
      isLoaded: true,
    });
  };
}

CSS:

.loader-container {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.4);
  animation: fadeIn 0.3s ease-out;
  z-index: 110;
  overflow: hidden;
}


.loader {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #0083db;
}

我正在使用Bootstrap 4依赖项,但如果您不使用,则这是类主体:

.position-relative {
  position: relative!important;
}

.h-100 {
  height: 100%!important;
}

.img-fluid {
  max-width: 100%;
  height: auto;
}

用法:

<LoadableImage path={'/image/path'} alt='Alternative text' />

您还可以将自定义参数添加到<img>标签。随时进行您的自定义装载机设计。

© www.soinside.com 2019 - 2024. All rights reserved.