React 中的图像 onError 处理

Image onError Handling in React

我正在尝试抓取多个 YouTube 缩略图的 maxresdefault。一些 YouTube 视频根本没有高分辨率缩略图,所以我想用 img 元素上的 onError 属性来捕捉它。出于某种原因,当我收到 404 img 错误时,我的功能没有触发。有任何想法吗?提前致谢。

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

例如,您可以创建一个 Image 对象,尝试加载 background 图像,并据此可靠地确定图像是否加载失败。在图像加载成功或失败时,您将在 <FeaturedVideo/> 组件上 setState() 使用适当的 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>
    )
  }
}

希望对您有所帮助!