在React JS中渲染实际图像之前如何渲染默认图像? [英] How to render default image before rendering the actual image in react js?

查看:55
本文介绍了在React JS中渲染实际图像之前如何渲染默认图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过这样的道具渲染图像:

I render image by props like this :

function AdImg(props) {
    const propImg = `http://localhost:5000/${props.img}`;
    return (
                <img
                    placeholder={require('../../../app-data/img/default.png')}
                    alt="ad-img"
                    className="img-fluid rounded"
                    src={propImg}
                />
    );
}

export default AdImg;

问题在于此组件渲染时,直到渲染实际图像时才显示占位符.

The propblem is when this component renders it doesn't show the placeholder till it render the actual image .

如何设置默认的占位符图像,使其在显示实际图像之前一直显示占位符?

How can I set a default placeholder image so it shows the placeholder till it renders the actual image ?

推荐答案

类似的方法应该起作用

export default function App() {
  const [isLoading, setIsLoading] = useState(true);

  function onLoad() {
    // delay for demo only
    setTimeout(() => setIsLoading(false), 1000);

   // setIsLoading(false)
  }

  return (
    <>
      <img
        alt="ad-img"
        width={300}
        src="https://via.placeholder.com/300x200/FF0000"
        style={{ display: isLoading ? "block" : "none" }}
      />
      <img
        alt="ad-img"
        width={300}
        src="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcS1hIjBaj0A0XNB_xAozRAcFs6Gr0DQhWTGiQ&usqp=CAU"
        style={{ display: isLoading ? "none" : "block" }}
        onLoad={onLoad}
      />
    </>
  );
}

...我们正在显示2张图片,占位符和实际图片.在加载实际图像时,我们将显示占位符,在加载占位符之后,我们将隐藏占位符并显示实际图像.

...we're displaying 2 images, the placeholder and the actual image. While the actual image is loading, we're going to display the placeholder, when its loaded we're going to hide the placeholder and show the actual image.

这篇关于在React JS中渲染实际图像之前如何渲染默认图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆