如何在react中替换图像源?

IT技术 reactjs react-native react-router react-redux
2021-05-04 15:32:03

你能告诉我如何在react中替换图像源吗?.我正在src为我的img标签设置一个网址如果服务器上不存在图像,我想将srcurl替换为这个http://punemirror.indiatimes.com/photo/55813567.cms

如果图像存在于服务器上,那么它很好。如果没有,那么我需要将源 url 更改为“ http://punemirror.indiatimes.com/photo/55813567.cms

这是我的代码 https://codesandbox.io/s/KOrGKp3B8

我像那样尝试

imageExists(url, callback) {
        var img = new Image();
        img.onload = function () {
            callback(true);
        };
        img.onerror = function () {
            callback(false);
        };
        img.src = url;
    }


    renderList() {
        const lis = this.items.map((item, key) => {
            var src = "http://mumbaimirror.indiatimes.com/photo/" + item.id + ".cms";
            const alt = "http://punemirror.indiatimes.com/photo/55813567.cms";

            return (
                <li key={key}>
                    <a><img src={src}/><span>{item.hl}</span></a>
                </li>
            )
        })
        return (
            <ul>
                {lis}
            </ul>
        )
    }

    render() {
        return (
            <div className="list">
                {this.renderList()}
            </div>
        )
    }
}
4个回答

检查您的图像是否存在,使用此方法,然后在您的组件类中:

componentWillMount() {
  var url = "http://mumbaimirror.indiatimes.com/photo/" + item.id + ".cms";
  const alt = "http://punemirror.indiatimes.com/photo/55813567.cms";
  var src = this.imageExists(url) ? url : alt;
  this.setState({ src });
}

// added from the mentioned post
function imageExists(image_url){
    var http = new XMLHttpRequest();
    http.open('HEAD', image_url, false);
    http.send();
    return http.status != 404;
}

render() {
    var src = this.state.src;
    ...
}

您可以为此使用对象。

<object data={src} type="image/png">
  <img src="http://punemirror.indiatimes.com/photo/55813567.cms" />
</object>

在组件渲染中,您需要检查服务器端是否存在所有现有文件,并返回ids您在服务器上获得的所有文件的数组

当您获得现有文件的数组时,让我们调用它allFileIds,您只需要执行以下操作:

<li key={key}>
                <a><img src={allFileIds.indexOf(item.id) !== -1 ? src : alt}/><span>{item.hl}</span></a>
</li>

这将检查是否在id服务器上找到所需的(它检查服务器返回item.id的文件数组中是否存在ids),如果不存在,则呈现alt属性而不是src. 我希望这很清楚!

首先将您的图像集合放在状态而不是字段中。

我假设您的图片集合中的每张图片都至少包含一个字段:url。您可以在 componentDidMount/componentWillReceiveProps 中检查您的图像 (this.items) 是否存在。请注意,您的imageExists方法是异步的 - 因此您不能在渲染期间使用它。根据检查,您可以将 img.src 设置为未定义/空或有效 URL。

然后在渲染检查 image.url ,如果它丢失 - 使用默认的。