首页 > 解决方案 > img 标签有点滞后,显示旧页面图像一两秒钟,然后在 react 中显示新图像

问题描述

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

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

标签: reactjsimagelag

解决方案


从您提供的信息来看,很难在我们没有看到的情况下分享解决方案。我可以建议您为图像添加一个加载器,以便为您带来更好的用户体验。尝试以下操作:

 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>标签添加自定义参数。随意制作您的自定义装载机设计。


推荐阅读