How to render default image before rendering the actual image in react js?

青春壹個敷衍的年華 提交于 2021-01-29 06:12:07

问题


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 ?


回答1:


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. 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.



来源:https://stackoverflow.com/questions/63896591/how-to-render-default-image-before-rendering-the-actual-image-in-react-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!