react.js Replace img src onerror

后端 未结 22 3063
北恋
北恋 2020-11-29 00:20

I have a react component that is the detail view from a list.

I am trying to replace the image with a default image if the image does not exist and there is a 404 er

22条回答
  •  北海茫月
    2020-11-29 01:27

    I took @Skay's answer and created a reusable Image component. Posting in case it helps anyone:

    import React, { PropTypes } from 'react';
    
    const Image = ({src, fallbackSrc, ...other}) => {
        let element;
        const changeSrc = newSrc => {
            element.src = newSrc;
        };
        return (
             changeSrc(fallbackSrc)} 
                 ref={el => element=el} 
                 {...other} />
        );
    };
    
    Image.propTypes = {
        src: PropTypes.string,
        fallbackSrc: PropTypes.string
    };
    export default Image;

提交回复
热议问题