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)
你的接口声明NavLinkProps是错误的。您不应该添加,props因为您正在传播对象的其余部分,这将是界面中href、exact和之后的任何内容children。界面应该如下所示:
interface NavLinkProps {\n href: string\n exact?: boolean\n children: ReactNode\n className: string\n // any other props you might have\n}\nRun Code Online (Sandbox Code Playgroud)\n因此传播 \xe2\x80\x93 时存在的 props 对象...props将是:
interface NavLinkProps {\n href: string\n exact?: boolean\n children: ReactNode\n className: string\n // any other props you might have\n}\nRun Code Online (Sandbox Code Playgroud)\n有关更多信息,请参阅此文档 \xe2\x80\x93 https://reactjs.org/docs/jsx-in-depth.html#spread-attributes
\n| 归档时间: |
|
| 查看次数: |
13407 次 |
| 最近记录: |