属性 'className' 不存在于类型 '{ props: ReactNode; }'
Property 'className' does not exist on type '{ props: ReactNode; }'
我目前正在将一个 Next.js 项目从 JavaScript 迁移到 TypeScript,我 运行 遇到错误:Property 'className' does not exist on type '{ props: ReactNode; }'
。在 Javascript 中,我可以从 props 中提取 className,但 typescript 找不到类型。这是代码:
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>
)
}
}
您的界面声明 NavLinkProps
是错误的。您不应该添加 props
,因为您正在传播对象的其余部分,这些对象可能是界面中 href
、exact
和 children
之后的任何内容。界面应如下所示:
interface NavLinkProps {
href: string
exact?: boolean
children: ReactNode
className: string
// any other props you might have
}
因此传播存在的道具对象 – ...props
将是:
{
className,
// any other props you might have
}
查看此文档了解更多信息 – https://reactjs.org/docs/jsx-in-depth.html#spread-attributes
我目前正在将一个 Next.js 项目从 JavaScript 迁移到 TypeScript,我 运行 遇到错误:Property 'className' does not exist on type '{ props: ReactNode; }'
。在 Javascript 中,我可以从 props 中提取 className,但 typescript 找不到类型。这是代码:
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>
)
}
}
您的界面声明 NavLinkProps
是错误的。您不应该添加 props
,因为您正在传播对象的其余部分,这些对象可能是界面中 href
、exact
和 children
之后的任何内容。界面应如下所示:
interface NavLinkProps {
href: string
exact?: boolean
children: ReactNode
className: string
// any other props you might have
}
因此传播存在的道具对象 – ...props
将是:
{
className,
// any other props you might have
}
查看此文档了解更多信息 – https://reactjs.org/docs/jsx-in-depth.html#spread-attributes