TS2339:类型'(props:any)=> DetailsReactHTMLElement <{className:string; },HTMLElement>'

时间:2019-03-25 21:31:26

标签: reactjs typescript typescript-typings typescript2.0

我尝试使用TypeScript为无状态的功能性React组件指定默认道具,并使用以下代码:

import React from 'react'

interface Props {
  readonly sid?: string,
}

const defaultProps: any = {
  sid: '',
}

const ModalBackdrop: React.SFC<Props> = (props: Props): JSX.Element => {
  const { sid } = props

  return (
    <div className={`ModalBackdrop ModalBackdrop_${sid} ModalBackdrop__hide`} />
  )
}

ModalBackdrop.defaultProps = defaultProps

export default ModalBackdrop

当我编译代码时,出现以下错误消息:

TS2339: Property 'defaultProps' does not exist on type '(props: any) => DetailedReactHTMLElement<{ className: string; }, HTMLElement>'.

我「wdm」:编译失败。

我想念什么?

2 个答案:

答案 0 :(得分:0)

最后,我找到了以下解决方案,用于为无状态的功能性React组件设置默认属性。关键行是const propsPrivate: Props = { ...defaultProps, ...props }

import React from 'react'

interface Props {
  readonly sid?: string,
}

const defaultProps: any = {
  sid: '',
}

export const ModalBackdrop: React.SFC<Props> = (props: Props): JSX.Element => {
  const propsPrivate: Props = { ...defaultProps, ...props }
  const { sid } = propsPrivate

  return (
    <div className={`ModalBackdrop ModalBackdrop_${sid} ModalBackdrop__hide`} />
  )
}

答案 1 :(得分:0)

您可以使用函数符号代替 const

import React from 'react'

interface Props {
  sid?: string,
}

const defaultProps: any = {
  sid: '',
}

function ModalBackdrop(props: Props): JSX.Element {
  const { sid } = props

  return (
    <div className={`ModalBackdrop ModalBackdrop_${sid} ModalBackdrop__hide`} />
  )
}

ModalBackdrop.defaultProps = defaultProps

export default ModalBackdrop

function ModalBackdrop(props: Props): JSX.Element 行中唯一的变化。