reactjs - img 标签有点滞后,显示旧页面图像一两秒钟,然后在 react 中显示新图像
问题描述
该页面有一个 prev 和 next 按钮,可以让我们遍历页面,在包含图像的卡片行中显示数据。在第一次单击上一个按钮的下一个按钮时,文本字段会立即显示,但 img 标签有点滞后,显示旧页面图像一两秒钟,然后在反应中显示新图像。
知道如何防止这种情况吗?或者至少让第一张图片立即消失?
解决方案
从您提供的信息来看,很难在我们没有看到的情况下分享解决方案。我可以建议您为图像添加一个加载器,以便为您带来更好的用户体验。尝试以下操作:
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>
标签添加自定义参数。随意制作您的自定义装载机设计。
推荐阅读
- java - 多线程的 SQLite 访问队列(用于写入和读取命令)
- html - 在 django html 模板中比较日期时间对象的问题
- python - 在 AWS Lambda 脚本中使用多个 Python 函数
- typescript - 带有属性注入的打字稿高阶函数
- ajax - 带有空格的 Solr 查询,仅 (#q=%20) 停顿
- node.js - 如何在同一个项目Node.js中将一个GAE服务列入另一个白名单
- html - 暂停 CSS 动画并在悬停时更改动画属性 - 但不要在鼠标离开时重新启动另一个动画
- python - 在这个 django settings.py python 列表中正斜杠做什么?
- excel - VBA DateAdd() 函数未向每个后续月份添加正确的天数
- cypress - 如何等待 api 调用完成,然后使用 cypress 检查元素是否存在?