【问题标题】:Property 'className' does not exist on type '{ props: ReactNode; }'类型'{ props: ReactNode; 上不存在属性'className' }'
【发布时间】:2021-10-15 04:48:31
【问题描述】:

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

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>
  )
}

}

【问题讨论】:

  • 只需将 className?: string 添加到您的 NavLinkProps 接口并处理未定义的 className 情况。
  • 这对修改你拥有的道具来说是一个糟糕的模式。
  • @RomanKurbatov 更好的模式是什么?
  • 试试classnames 包,它将简化处理多个类。您可以使用 {...props} {className: {classnames(props.className, { active: isActive }} 之类的东西来覆盖原始类名并具有多个条件。
  • 谢谢!这行得通。

标签: javascript reactjs typescript next.js rest-parameters


【解决方案1】:

您的界面声明NavLinkProps 是错误的。您不应该添加props,因为您正在传播对象的其余部分,这些对象将是href、exact 和children 之后界面中的任何内容。界面应该是这样的:

interface NavLinkProps {
  href: string
  exact?: boolean
  children: ReactNode
  className: string
  // any other props you might have
}

所以传播存在的 props 对象 - ...props 将是:

{
  className,
  // any other props you might have
}

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

【讨论】:

    猜你喜欢
    • 2021-07-12
    • 2021-02-06
    • 2020-09-03
    • 1970-01-01
    • 2020-11-07
    • 2020-01-24
    • 2021-08-20
    • 1970-01-01
    • 2018-09-01
    相关资源
    最近更新 更多