React中的图像onError处理

时间:2018-10-25 23:32:04

标签: javascript reactjs image youtube onerror

我正在尝试获取多个YouTube缩略图中的+-----------+-----+---------------+ | Canada | USA | Stackoverflow | +-----------+-----+---------------+ | 62941ZPA6 | | USER | | 62943Z4R0 | | USER | | 62945ZLQ1 | | USER | | 62950ZZE5 | | USER | | 75585RLK9 | | USER | | 00433JAA3 | | USER | | 13509PEV1 | | USER | | 13509PEZ2 | | USER | | 62931ZLX2 | | USER | | 62941Z8M9 | | USER | | 62941ZYK4 | | USER | | 62942ZV42 | | USER | | 62943Z6T4 | | USER | | 62946Z6Y0 | | USER | | 62947ZWC8 | | USER | | 62948ZTJ6 | | USER | | 62949ZE51 | | USER | | 75585RLK9 | | USER | | 75585RMB8 | | USER | | 75585RMW2 | | USER | +-----------+-----+---------------+ 。有些YouTube视频根本没有高分辨率的缩略图,因此我想在img元素上使用onError属性来捕捉它。由于某些原因,当我收到404 img错误时,我的功能没有触发。有任何想法吗?预先感谢。

maxresdefault

1 个答案:

答案 0 :(得分:1)

要实现这一目标,我建议根据您的<img />组件的状态来渲染<FeatureVideo/>

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

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

希望有帮助!