简体   繁体   English

如何在渲染 React js 中的实际图像之前渲染默认图像?

[英]How to render default image before rendering the actual image in 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?如何设置默认占位符图像,以便在呈现实际图像之前显示占位符?

Something like this should work这样的事情应该工作

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}
      />
    </>
  );
}

...we're displaying 2 images, the placeholder and the actual image. ...我们正在显示 2 张图像,占位符和实际图像。 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.在加载实际图像时,我们将显示占位符,加载后我们将隐藏占位符并显示实际图像。

编辑古怪的微风-kp7yg

For me it work only after I change the second image style (the one that we want to show once it loaded), to {visibility: loading? 'hidden': 'visible'}对我来说,只有在我将第二个图像样式(加载后我们想要显示的样式)更改为{visibility: loading? 'hidden': 'visible'} {visibility: loading? 'hidden': 'visible'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM