React中的图像onError处理 [英] Image onError Handling in React

查看:142
本文介绍了React中的图像onError处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取多个YouTube缩略图的maxresdefault.有些YouTube视频根本没有高分辨率的缩略图,因此我想在img元素上使用onError道具来捕捉它.由于某种原因,当我收到404 img错误时,我的函数没有被触发.有任何想法吗?预先感谢.

I am trying to grab the maxresdefault of multiple YouTube thumbnails. Some YouTube videos simply don't have a high res thumbnail photo so I want to catch that with an onError prop on an img element. For some reason my function is not triggering when I get the 404 img error. Any ideas? Thanks in advance.

class FeaturedVideo extends Component<Props> {
  addDefaultSrc = (e) => {
    e.target.src = this.props.background.replace("maxresdefault", "hqdefault")
  }

  renderVideo = (props) => (
    <div
      style={{
        width: "100%",
        height: "100%",
        backgroundSize: "contain",
      }}
      className="featured-community-video"
    >
      <img onError={this.addDefaultSrc} src={props.background} alt="" />
      <div className="featured-community-video-title">
        <h2 style={{ fontSize: "0.8em" }}>WATCH</h2>
        <h1 style={{ fontSize: props.titleFontSize }}>{props.title}</h1>
      </div>
    </div>
  )

  render() {
    return (
      <div
        key={this.props.postId}
        style={{
          width: this.props.width,
          height: "50%",
        }}
        className="featured-community-video-container"
      >
        <Link to={routeCodes.POST_DETAILS(this.props.postId)}>
          {this.renderVideo(this.props)}
        </Link>
      </div>
    )
  }
}

推荐答案

为实现此目的,我建议根据您<FeatureVideo/>组件的状态渲染<img />.

To achieve this, I would suggest rendering the <img /> based on the state of your <FeatureVideo/> component.

例如,您可以创建一个Image对象,尝试加载background图像,从而可靠地确定该图像是否无法加载.在成功加载或失败图像后,您将在<FeaturedVideo/>组件上使用适当的backgroundsetState(),该值将用于呈现实际的<img/>元素:

You could for instance, create an Image object, attempt to load the background image and by this, reliably determine if the image fails to load. On the images success or failure to load, you would then setState() on your <FeaturedVideo/> component with the appropriate background value which would instead be used to rendering you actual <img/> element:

class FeaturedVideo extends Component<Props> {

  componentDidMount() {

    if(this.props.background) {

      // When component mounts, create an image object and attempt to load background
      fetch(this.props.background).then(response => {
         if(response.ok) {
           // On success, set the background state from background
           // prop
           this.setState({ background : this.props.background })
         } else {        
           // On failure to load, set the "default" background state
           this.setState({ background : this.props.background.replace("maxresdefault", "hqdefault") })
         }
      });
    }
  }

  // Update the function signature to be class method to make state access eaiser
  renderVideo(props) {

    return <div
      style={{
        width: "100%",
        height: "100%",
        backgroundSize: "contain",
      }}
      className="featured-community-video">

      {/* Update image src to come from state */}

      <img src={this.state.background} alt="" />
      <div className="featured-community-video-title">
        <h2 style={{ fontSize: "0.8em" }}>WATCH</h2>
        <h1 style={{ fontSize: props.titleFontSize }}>{props.title}</h1>
      </div>
    </div>
  }

  render() {
    return (
      <div
        key={this.props.postId}
        style={{
          width: this.props.width,
          height: "50%",
        }}
        className="featured-community-video-container"
      >
        <Link to={routeCodes.POST_DETAILS(this.props.postId)}>
          {this.renderVideo(this.props)}
        </Link>
      </div>
    )
  }
}

希望有帮助!

这篇关于React中的图像onError处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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