ReactJS-UseRef,而不是useChange来代替道具

问题描述 投票:0回答:1

我具有以下ImageFallback组件。当原始图像不存在时,它会提供备用svg图像。

export interface ImageProps {
  srcImage: string;
  classNames?: string;
  fallbackImage?: FallbackImages;
}

const Image = ({
  srcImage,
  classNames,
  fallbackImage = FallbackImages.GENERAL_FALLBACK
}: ImageProps) => {
  const imgToSourceFrom = `srcImage`;
  const imgToFallbackTo = `fallbackImage`;

  const [imgUrl, setImgUrl] = useState<string>(imgToSourceFrom);

  return <img src={imgUrl} className={classNames} onError={() => setImgUrl(imgToFallbackTo)} />;
};

export default Image;

现在我想使用useRef而不是useState进行相同的操作。我有点困惑,因为我不经常使用ref vey。 所以,任何想法,当调用useRef时如何利用onError来更改图像的来源?

我尝试过,但是没有运气:

  const imageRef = useRef(imgToFallbackTo);

  console.log(imageRef.current); // this print the fallback..
  return <img src={imgToSourceFrom} className={classNames} onError={() => imageRef.current} />;
javascript reactjs typescript image react-hooks
1个回答
0
投票

所以,不确定,我最终得到的结果是好是坏,但它可以正常工作,并且我的测试通过了。

export interface ImageProps {
  srcImage: string;
  classNames?: string;
  fallbackImage?: FallbackImages;
}

const Image = ({
  srcImage,
  classNames,
  fallbackImage = FallbackImages.FALLBACK
}: ImageProps) => {
  const imgToSourceFrom = srcImage;
  const imgToFallbackTo = fallbackImage;

  const imageRef = useRef(null);
  const whenImageIsMissing = () => {
    imageRef.current.src = imgToFallbackTo;
  };

  return (
    <img ref={imageRef} src={imgToSourceFrom} className={classNames} onError={whenImageIsMissing} />
  );
};

export default Image;

如果您知道更好的解决方案,请随时发布。

© www.soinside.com 2019 - 2024. All rights reserved.