我有一个react组件,它是列表中的详细信息视图。
我试图用默认图像替换该图像,如果该图像不存在并且出现404错误。
我通常会在img标签中使用onerror方法,但这似乎不起作用。
我不确定如何做出反应。
这是我的组件:
import React from 'react'; import {Link} from 'react-router'; import ContactStore from '../stores/ContactStore' import ContactActions from '../actions/ContactActions'; class Contact extends React.Component { constructor(props) { super(props); this.state = ContactStore.getState(); this.onChange = this.onChange.bind(this); } componentDidMount() { ContactStore.listen(this.onChange); ContactActions.getContact(this.props.params.id); } componentWillUnmount() { ContactStore.unlisten(this.onChange); } componentDidUpdate(prevProps) { if (prevProps.params.id !== this.props.params.id) { ContactActions.getContact(this.props.params.id); } } onChange(state) { this.setState(state); } render() { return ( <div className='container'> <div className='list-group'> <div className='list-group-item animated fadeIn'> <h4>{this.state.contact.displayname}</h4> <img src={this.state.imageUrl} /> </div> </div> </div> ); } } export default Contact;
由于没有完美的答案,因此我正在发布我使用的代码段。我正在使用Image回退到的可重用组件fallbackSrc。
Image
fallbackSrc
由于后备图片可能再次失败并触发无限次重新渲染循环,因此我添加了errored状态。
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, };