javascript - การตั้งค่า ref บนคอมโพเนนต์ Image ของ NextJS ทำให้เกิดข้อผิดพลาดของ typescript
ฉันกำลังพยายามปรับโครงสร้างใหม่หนึ่งในคอมโพเนนต์ของฉันเพื่อใช้ TypeScript ดังที่คุณเห็นด้านล่าง ฉันกำลังใช้การอ้างอิงในคอมโพเนนต์ Image ของ NextJS และพยายามตั้งค่าประเภท
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
จากนั้นฉันจะได้รับข้อผิดพลาด TypeScript ดังต่อไปนี้บนคุณสมบัติ Image ref:
(สมบัติ) ref: RefObject ประเภท '{ className: string; src: string | StaticImport; alt: string | undefined; width: string | number | undefined; height: string | number | undefined; ref: RefObject; }' ไม่สามารถกำหนดให้กับประเภท 'IntrinsicAttributes & Omit
มันเกิดขึ้นเพราะในไฟล์ next/dist/client/image.d.ts ประเภทของ ref ถูกละไว้ใน 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;
};
ข้อผิดพลาดหายไปเมื่อฉันลบ | 'ref' ออกจากรายการคุณสมบัติที่ละเว้น ทำไมคุณสมบัตินี้ถึงถูกละเว้น? การใช้คุณสมบัติ ref บนคอมโพเนนต์ Image ถือว่าเป็นแนวปฏิบัติที่ไม่ดีหรือไม่? สามารถแก้ไขได้ง่ายโดยการใส่ div หุ้มรอบคอมโพเนนต์ image และเพิ่มการอ้างอิงที่นั่น แต่ฉันสงสัยว่าทำไมจึงทำไม่ได้และฉันกำลังทำถูกต้องหรือไม่
คำตอบ #1
การส่ง ref ไปยัง next/image ดูเหมือนว่าจะถูกเพิ่มใน next 13.0.6.