类型“StaticImageData”不可分配给类型“string”

ran*_*ote 18 javascript typescript reactjs next.js

我在我的小学习 NextJS 和 TypeScript 项目的界面上遇到了困难。我以为我已经解决了这个问题,但是当涉及到我的组件src上的 prop时,我正在处理 Header.tsx 上的问题Header。我不断收到以下错误消息

类型“StaticImageData”不可分配给类型“string”。预期的类型来自属性“src”,该属性在类型“IntrinsicAttributes & ILogo & {children?: ReactNode;”上声明。}'

我仍然对理解儿童道具以及如何使它们从父母流向孩子充满信心,这使得这样的错误有点令人沮丧。

我已经在下面发布了脚趾代码,并欢迎提出建议,以解决眼前的问题,以及将来缓解此问题的方法。

标头.tsx

import React from "react";
import Navbar from "./Navbar/Navbar";
import Logo from "../Logo";
import companyLogo from "../../../public/assets/images/logo.png";
import { ILogo } from "../../types/headerType";

const Header = () => {
  return (
    <div className="container flex justify-between h-16 max-w-full bg-pink-400 h-100px">
      <Logo className="object-cover" src={companyLogo} />
      <Navbar />
    </div>
  );
};

export default Header;
Run Code Online (Sandbox Code Playgroud)

标志.tsx

import Image from "next/image";
import Link from "next/link";
import React, { FunctionComponent } from "react";
import { ILogo } from "../types/headerType";

const Logo: FunctionComponent<ILogo> = ({ src }) => {
  return (
    <div>
      <Link href="/">
        <a>
          <Image
            src={src}
            alt="Logo"
            className="object-cover cursor-pointer"
            height="100px"
            width="320px"
            layout="intrinsic"
          />
        </a>
      </Link>
    </div>
  );
};

export default Logo;
Run Code Online (Sandbox Code Playgroud)

headerType.ts

export interface ILogo {
  //   image: HTMLImageElement;
  src: string;
  className?: string;
}
Run Code Online (Sandbox Code Playgroud)

Pep*_*rez 32

您可以在控制台中打印导入图像的结果。如果你得到类似 [object object] 的东西,那么你需要询问对象中特定的 src 属性:

<Logo className="object-cover" src={companyLogo.src} />
Run Code Online (Sandbox Code Playgroud)


小智 4

您正在传递本地静态图像,因此需要将其添加到类型中,而不是

export interface ILogo {
  //   image: HTMLImageElement;
  src: string;
  className?: string;
}
Run Code Online (Sandbox Code Playgroud)

你可以有这个

export interface ILogo {
  //   image: HTMLImageElement;
  src: string | StaticImageData;
  className?: string;
}
Run Code Online (Sandbox Code Playgroud)