属性“className”在类型“{ props:ReactNode;”上不存在 }'

Gra*_*y59 5 javascript typescript reactjs next.js rest-parameters

我目前正在将 Next.js 项目从 JavaScript 迁移到 TypeScript,但遇到了错误:Property 'className' does not exist on type '{ props: ReactNode; }'。在 Javascript 中,我可以从 props 中提取 className,但打字稿找不到类型。这是代码:

import { useRouter } from 'next/router'
import Link from 'next/link'
import { ReactNode } from 'react'

export { NavLink }

NavLink.defaultProps = {
  exact: false,
}

interface NavLinkProps {
  href: string
  exact?: boolean
  children: ReactNode
  props: ReactNode
}

function NavLink({ href, exact, children, ...props }: NavLinkProps) {
  const { pathname } = useRouter()
  const isActive = exact ? pathname === href : pathname.startsWith(href)

  if (isActive) {
    props.className += ' active'
  }

  return (
    <Link href={href}>
      <a {...props}>{children}</a>
    </Link>
  )
}

}
Run Code Online (Sandbox Code Playgroud)

Jos*_*osh 3

你的接口声明NavLinkProps是错误的。您不应该添加,props因为您正在传播对象的其余部分,这将是界面中hrefexact和之后的任何内容children。界面应该如下所示:

\n
interface NavLinkProps {\n  href: string\n  exact?: boolean\n  children: ReactNode\n  className: string\n  // any other props you might have\n}\n
Run Code Online (Sandbox Code Playgroud)\n

因此传播 \xe2\x80\x93 时存在的 props 对象...props将是:

\n
interface NavLinkProps {\n  href: string\n  exact?: boolean\n  children: ReactNode\n  className: string\n  // any other props you might have\n}\n
Run Code Online (Sandbox Code Playgroud)\n

有关更多信息,请参阅此文档 \xe2\x80\x93 https://reactjs.org/docs/jsx-in-depth.html#spread-attributes

\n