簡體   English   中英

在 NextJS Image 組件上設置 ref 會產生 typescript 錯誤

[英]Setting a ref on the NextJS Image component creates a typescript error

我正在嘗試重構我的一個組件以使用 typescript。如下所示,我正在使用 NextJS Image 組件上的引用並嘗試設置類型

import { useRef } from 'react'
import Image, { ImageProps } from 'next/image'


type BannerBlockProps = {
  image?: ImageProps[]
}

const BannerBlock = (props: BannerBlockProps) => {
  const imageRef = useRef<HTMLImageElement >(null)

  return (
  
        <div className='BannerBlock-imageWrapper' >
          <Image className="BannerBlock-image" src={image[0].src} alt={image[0].alt} width={image[0].width} height={image[0].height} ref={imageRef}/>
        </div>
  )
}

export default BannerBlock

然后我在 Image ref 屬性上收到以下typescript 錯誤::

(屬性) ref: RefObject Type '{ className: string; 來源:字符串 | 靜態導入; 替代:字符串 | 不明確的; 寬度:字符串 | 編號 | 不明確的; 高度:字符串 | 編號 | 不明確的; 參考:參考對象; }' 不可分配給類型 'IntrinsicAttributes & Omit<DetailedHTMLProps<ImgHTMLAttributes, HTMLImageElement>, "src" |... 4 更多... | “加載中”>&{...; }'。 類型“IntrinsicAttributes & Omit<DetailedHTMLProps<ImgHTMLAttributes, HTMLImageElement> 上不存在屬性“ref”,“src” |... 4 更多... | “加載”>&{

發生這種情況是因為在 next/dist/client/image.d.ts 中 ImageProps 上省略了 ref 類型:

export declare type ImageProps = Omit<JSX.IntrinsicElements['img'], 'src' | 'srcSet' | 'ref' | 'width' | 'height' | 'loading'> & {
    src: string | StaticImport;
    width?: number | string;
    height?: number | string;
    layout?: LayoutValue;
    loader?: ImageLoader;
    quality?: number | string;
    priority?: boolean;
    loading?: LoadingValue;
    lazyRoot?: React.RefObject<HTMLElement> | null;
    lazyBoundary?: string;
    placeholder?: PlaceholderValue;
    blurDataURL?: string;
    unoptimized?: boolean;
    objectFit?: ImgElementStyle['objectFit'];
    objectPosition?: ImgElementStyle['objectPosition'];
    onLoadingComplete?: OnLoadingComplete;
};

當我刪除| 'ref'時錯誤消失了省略屬性列表中的| 'ref' 為什么省略此屬性? 在 Image 組件上使用ref屬性是不好的做法嗎? 在圖像組件上放置一個包裝 div 並在那里添加引用很容易解決,但我很好奇為什么這是不可能的,以及我是否做對了。

將 ref 傳遞給 next/image 似乎是在 next 13.0.6中添加的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM