react.js Replace img src onerror

后端 未结 22 3120
北恋
北恋 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:13

    Try this custom Image component:

    import React, { useRef } from 'react';
    import PropTypes from 'prop-types';
    
    import defaultErrorImage from 'assets/images/default-placeholder-image.png';
    
    const Image = ({ src, alt, className, onErrorImage }) => {
      const imageEl = useRef(null);
      return (
        {alt} {
            imageEl.current.src = onErrorImage;
          }}
          ref={imageEl}
        />
      );
    };
    
    Image.defaultProps = {
      onErrorImage: defaultErrorImage,
    };
    
    Image.propTypes = {
      src: PropTypes.string.isRequired,
      alt: PropTypes.string.isRequired,
      className: PropTypes.string.isRequired,
      onErrorImage: PropTypes.string,
    };
    
    export default Image;
    

提交回复
热议问题