我目前正在將 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>
)
}
}
uj5u.com熱心網友回復:
你的介面宣告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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/315092.html
標籤:javascript 反应 打字稿 下一个.js 其余参数
下一篇:如何處理簡單物件的索引簽名
