使用可变类型来反应Typescript组件(来自props)

时间:2019-04-09 10:05:03

标签: reactjs typescript ref

我想创建一个从props和child接受其类型(例如'div','span')并进行渲染的组件,该组件还支持引用转发和className prop。

问题是我遇到了一个错误'className' does not exist on type 'IntrinsicAttributes,无法弄清楚是什么原因造成的。

我尝试将提供给forwardRef的类型从HTMLElement更改为不同的类型,通过谷歌搜索相似的组件,但这无济于事。

当我将HTMLElement更改为HTMLDivElement,并将<Component ...>更改为<div ...>时,此错误消失了。因此,问题可能出在错误的类型(HTMLElement

这是组件代码:

import React, { ReactChildren, ComponentType } from "react"

interface MyComponentProps {
  children: ReactChildren
  component: string | ComponentType
  className: string
}

const MyComponent = React.forwardRef<HTMLElement, MyComponentProps>(
  (props, ref) => {
    const { children, className, component: Component, ...otherProps } = props

    return (
      <Component className={className} ref={ref} {...otherProps}>
        {children}
      </Component>
    )
  },
)

MyComponent.defaultProps = {
  component: "div",
}

export default MyComponent

预期结果:没有打字稿错误。

实际结果:<Component className={className} ref={ref} {...otherProps}>行中出现以下错误

TS2322: Type '{ children: ReactChildren | (ReactChildren & string) | (ReactChildren & number) | (ReactChildren & false) | (ReactChildren & true) | (ReactChildren & ReactElement<any, string | ((props: any) => ReactElement<...> | null) | (new (props: any) => Component<...>)>) | (ReactChildren & ReactNodeArray) | (ReactChildren & Re...' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.
  Property 'className' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.

0 个答案:

没有答案