简体   繁体   中英

Setting a ref on the NextJS Image component creates a typescript error

I'm trying to refactor one of my components to use typescript. As you see below, I'm using a reference on the NextJS Image component and trying to set the type

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

I then get the following typescript error on the Image ref property: :

(property) ref: RefObject Type '{ className: string; src: string | StaticImport; alt: string | undefined; width: string | number | undefined; height: string | number | undefined; ref: RefObject; }' is not assignable to type 'IntrinsicAttributes & Omit<DetailedHTMLProps<ImgHTMLAttributes, HTMLImageElement>, "src" |... 4 more... | "loading"> & {...; }'. Property 'ref' does not exist on type 'IntrinsicAttributes & Omit<DetailedHTMLProps<ImgHTMLAttributes, HTMLImageElement>, "src" |... 4 more... | "loading"> & {

It happens because in next/dist/client/image.d.ts the ref type is omitted on the ImageProps:

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;
};

The error disappears when I remove | 'ref'| 'ref' from the list of omitted properties. Why is this property omitted? Is it bad practice to use the ref property on an Image component? It's easily fixed putting a wrapper div on the image component and add the reference there, but I am curious to why this is not possible and if I'm doing this right.

Passing ref to next/image seems to be added in next 13.0.6 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM