14

我正在使用 react dropzone 在我的简单应用程序中上传多张图片。为了显示要删除哪种类型的图像,我使用 TypeScript 制作了一个单独的组件。但 Next.js 图像 src 显示错误,如 Type:

'{ src: string; alt: string; }' is not assignable to type 'IntrinsicAttributes & ImageProps'.
  Type '{ src: string; alt: string; }' is not assignable to type 'ObjectImageProps'.
    Types of property 'src' are incompatible.
      Type 'string' is not assignable to type 'StaticImport'.

渲染文件.ts:

import { IFile } from "../../libs/types";
import { sizeInMb } from "../../libs/sizeInMb";
import { FunctionComponent } from "react";
import Image from "next/image"

const RenderFile: FunctionComponent<{
  file: IFile;
}> = ({ file: { formate, sizeInBytes, name } }) => {
  return (
    <div>
      <Image src={`/images/${formate}.png`} alt="image"/>
      <span>{name}</span>
      <span>{sizeInMb(sizeInBytes)}</span>
    </div>
  );
};

export default RenderFile;

类型.ts:

export interface IFile {
  name: string;
  sizeInBytes: number;
  formate: string | number;
  id?: string;
}

我在 src 道具中的错误是什么?

4

3 回答 3

14

问题是next/image'sImage期待相当复杂的类型ImageProps,因为它是道具:

type StringImageProps = {
  src: string
} & (
  | { width?: never; height?: never; layout: 'fill' }
  | {
      width: number | string
      height: number | string
      layout?: Exclude<LayoutValue, 'fill'>
    }
) &
  (
    | {
        placeholder?: Exclude<PlaceholderValue, 'blur'>
        blurDataURL?: never
      }
    | { placeholder: 'blur'; blurDataURL: string }
  )

type ObjectImageProps = {
  src: StaticImport
  width?: number | string
  height?: number | string
  layout?: LayoutValue
  placeholder?: PlaceholderValue
  blurDataURL?: never
}

export type ImageProps = Omit<
  JSX.IntrinsicElements['img'],
  'src' | 'srcSet' | 'ref' | 'width' | 'height' | 'loading' | 'style'
> & {
  loader?: ImageLoader
  quality?: number | string
  priority?: boolean
  loading?: LoadingValue
  unoptimized?: boolean
  objectFit?: ImgElementStyle['objectFit']
  objectPosition?: ImgElementStyle['objectPosition']
} & (StringImageProps | ObjectImageProps)

由于您不是从本地导入中导入图像,因此您剩下的唯一结构是StringImageProps. 为了符合它,您必须提供以下道具集之一:

<Image src={string} layout="fill" />
// or
<Image src={string} width={number} height={number} /> // with optional `layout` prop but not of type 'fill'

两种变体都可以使用可选placeholder(不是“模糊”类型)或必需的placeholder: 'blur' blurDataURL: string.

只有在那之后,您才能将 nativeimage的属性提供为alt.

于 2021-06-27T07:05:26.647 回答
0

我省略placeholderblurDataURLlayout。我也明确表示src为字符串。有关此问题的更多信息:https ://github.com/vercel/next.js/issues/26735

于 2021-07-13T16:59:42.080 回答
-2

只需将字符串转换为 any

<Image src={'string' as any} alt='Pic' />
于 2021-08-02T06:08:54.137 回答