【问题标题】:img tag lags a bit, showing the old page image for a second or two, and then showing the new image in reactimg 标签有点滞后,显示旧页面图像一两秒,然后在 react 中显示新图像
【发布时间】:2020-04-20 09:35:53
【问题描述】:

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

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

【问题讨论】:

  • 提供您尝试过的代码,这会给您带来问题..

标签: reactjs image lag


【解决方案1】:

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

 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' />

您还可以将自定义参数添加到 &lt;img&gt; 标记。随意制作您的自定义加载程序设计。

【讨论】:

  • 谢谢@Enchew,根据我的应用程序的要求创建了一个自定义加载器
猜你喜欢
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 2021-02-17
  • 2021-11-30
  • 2014-09-29
  • 1970-01-01
  • 2018-03-21
相关资源
最近更新 更多