【发布时间】:2021-10-17 05:47:45
【问题描述】:
用 react 为img 制作“出现”效果的正确方法是什么?
我们有什么:
const ProductCard = ({product}) => {
const [imgLoading, setImgLoading] = useState(true);
const onLoad = () => {
setImgLoading(false);
};
return (
<div className={classNames({
'product-card': true,
'img-loading': imgLoading,
})}
>
<img
src={product.photo}
alt={product.name}
onLoad={onLoad}
/>
<div className='img-cover'></div>
{/* ... */}
</div>
);
};
我使用 img-loading 类在加载时覆盖图像。
.product-card {
position: relative;
.img-cover {
position: absolute;
inset: 0;
background-color: #000;
opacity: 0;
transition: opacity 1.75s;
}
&.img-loading .img-cover {
opacity: 1;
}
}
当用户转到另一个页面(路线)时,Prop product 会发生变化。
第一次效果很好:当新产品涉及道具时,它会按预期呈现。
但是当用户回到他已经访问过的页面并从缓存中加载 img 时,它呈现没有我设置的效果,它只是立即显示。我认为这与缓存有关,因为当我在 chrome 开发工具中打开 Disable cache 时,它非常适合我。
【问题讨论】:
标签: css reactjs transition react-router-dom