react.js Replace img src onerror

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

    Previous versions have the bug; they don't count that src could be changed. So I made my ultimate solution and it:

    1. Supports typing
    2. Support case when src is changed
    3. Forwards ref
    4. Doesn't ignore onError (means you can pass onError to ImageWithFallback like you usually do with )

    Here it is:

    import React, { useState, useCallback, useEffect } from 'react';
    import noImage from 'src/svg/no-image.svg';
    
    export const ImageWithFallback = React.forwardRef(
      (
        {
          onError,
          ...props
        }: React.DetailedHTMLProps<
          React.ImgHTMLAttributes,
          HTMLImageElement
        >,
        ref: React.Ref,
      ) => {
        const [imageLoadFailed, setImageLoadFailed] = useState(false);
    
        const handleError = useCallback(
          (e: React.SyntheticEvent) => {
            if (imageLoadFailed) return;
            setImageLoadFailed(true); // to avoid infinite loop
            if (onError) {
              onError(e);
            }
          },
          [imageLoadFailed, setImageLoadFailed, onError],
        );
    
        useEffect(() => {
          setImageLoadFailed(false); // in case `src` is changed
        }, [props.src]);
    
        return (
          
        );
      },
    );
    

提交回复
热议问题