由于没有完美的答案,因此我正在发布我使用的代码段。我正在使用
Image回退到的可重用组件
fallbackSrc。
由于后备图片可能再次失败并触发无限次重新渲染循环,因此我添加了
errored状态。
import React, { Component } from 'react';import PropTypes from 'prop-types';class Image extends Component { constructor(props) { super(props); this.state = { src: props.src, errored: false, }; } onError = () => { if (!this.state.errored) { this.setState({ src: this.props.fallbackSrc, errored: true, }); } } render() { const { src } = this.state; const { src: _1, fallbackSrc: _2, ...props } = this.props; return ( <img src={src} onError={this.onError} {...props} /> ); }}Image.propTypes = { src: PropTypes.string, fallbackSrc: PropTypes.string,};


