使用条件渲染时,不会调用图像标签上的 React onLoad 事件 [英] React onLoad event on image tag is not getting called when using conditional render

查看:57
本文介绍了使用条件渲染时,不会调用图像标签上的 React onLoad 事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用无状态功能组件在从外部资源加载图像时添加微调器,如下所示:

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

并像这样使用它:

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

为什么 onLoad 永远不会被调用?

Why would the onLoad never get called?

推荐答案

当图像未加载时,您实际上并未渲染图像.您需要渲染它以使其 onLoad 触发

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

这篇关于使用条件渲染时,不会调用图像标签上的 React onLoad 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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