【问题标题】:Type 'StaticImageData' is not assignable to type 'string'类型“StaticImageData”不可分配给类型“字符串”
【发布时间】:2022-05-09 08:08:36
【问题描述】:

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

类型“StaticImageData”不可分配给类型“字符串”。这 预期类型来自属性“src”,它在此处声明类型 'IntrinsicAttributes & ILogo & { children?: ReactNode; }'

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

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

Header.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;

Logo.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;

headerType.ts

export interface ILogo {
  //   image: HTMLImageElement;
  src: string;
  className?: string;
}

【问题讨论】:

    标签: javascript reactjs typescript next.js


    【解决方案1】:

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

    <Logo className="object-cover" src={companyLogo.src} />
    

    【讨论】:

      【解决方案2】:

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

      export interface ILogo {
        //   image: HTMLImageElement;
        src: string;
        className?: string;
      }
      

      你可以拥有这个

      export interface ILogo {
        //   image: HTMLImageElement;
        src: string | StaticImageData;
        className?: string;
      }
      

      【讨论】:

        猜你喜欢
        • 2021-02-22
        • 2020-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多