reactjs 类型'StaticImageData'无法指派给类型'string'

aiqt4smr  于 2022-11-04  发布在  React
关注(0)|答案(3)|浏览(534)

我正在努力学习NextJS和TypeScript项目的接口。我以为我已经解决了这个问题,但是当我的Header组件的src属性出现问题时,我正在处理我的Header.tsx。我一直收到以下错误信息
类型'StaticImageData'无法指派给类型'string'。预期的类型来自此处在类型'IntrinsicAttributes & ILogo & { children??上宣告的属性'src':React节点; }'
我仍然不完全有信心理解儿童道具,以及如何使它们从父母流到孩子,这使得这样一个错误有点令人沮丧。
我已经继续前进,并张贴脚趾代码下面,欢迎和建议,都解决眼前的问题,并在未来减轻这一点的方法。

标题.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;

徽标.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;

标头类型.ts

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

ivqmmu1c1#

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

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

wbgh16ku2#

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

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

这个给你

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

niwlg2el3#

或者,它更易于用途:

import React from "react";
import Navbar from "./Navbar/Navbar";
import Image from 'next/image';
import companyLogo from "../../../public/assets/images/logo.png";

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

export default Header;

相关问题