React onLoad event on image tag is not getting called when using conditional render

心已入冬 提交于 2021-02-07 19:15:31

问题


I'm using the stateless functional component to add spinner while image is loading from the external resource, like so:

function ExternalImage(props) {
  const [loaded, setLoaded] = useState(false);
  function onLoad() {
    console.log('loaded');
    setLoaded(true);
  }
  return loaded
     ? <img 
        onLoad={onLoad}
        src={props.src}
        alt={props.alt}
        {...props} 
       /> 
     : <Spin />
}

And use it like so:

<ExternalImage src={image.src} alt={image.alt} className="image" />

Why would the onLoad never get called?


回答1:


When image is not loaded you aren't actually rendering the image. You need to render it for its onLoad to fire

function ExternalImage(props) {
  const [loaded, setLoaded] = useState(false);
  function onLoad() {
    console.log('loaded');
    setLoaded(true);
  }
  return (
    <>
        <img 
        style={{display: loaded? 'block': 'none'}}
        onLoad={onLoad}
        src={props.src}
        alt={props.alt}
        {...props} 
       /> 
       {!loaded && <Spin /> }
    </>
  )
}



回答2:


Your condition in return statement prevent rendering image, so it will be never loaded.

function ExternalImage(props) {
  const [loaded, setLoaded] = useState(false);
  function onLoad() {
    console.log('loaded');
    setLoaded(true);
  }

  return (
    <>
      <img 
        onLoad={onLoad}
        src={props.src}
        alt={props.alt}
        {...props} 
      /> 
      {!loaded && <Spin />}
    </>
  )
}

Also, remember to use useCallback hook to memoize your onLoad function:

function ExternalImage(props) {
  const [loaded, setLoaded] = useState(false);
  const onLoad = useCallback(() => {
    console.log('loaded');
    setLoaded(true);
  }, [])

  return (
    <>
      <img 
        onLoad={onLoad}
        src={props.src}
        alt={props.alt}
        {...props} 
      /> 
      {!loaded && <Spin />}
    </>
  )
}


来源:https://stackoverflow.com/questions/57162865/react-onload-event-on-image-tag-is-not-getting-called-when-using-conditional-ren

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