在react?无状态组件中使用打字稿无法分配给类型'React.SFC'

cod*_*ant 12 typescript reactjs

打字稿:2.8.3
@类型/反应:16.3.14


JSX.Element当我将组件声明为React.SFC(的别名 React.StatelessComponent)时,函数component的返回类型为。

发生了三个错误?

  1. TS2322: Type 'Element' is not assignable to type 'StatelessComponent<{}>', Type 'Element' provides no match for the signature '(props: { children?: ReactNode; }, context?: any): ReactElement<any>'

  2. TS2339: Property 'propTypes' does not exist on type '(props: LayoutProps) => StatelessComponent<{}>'

  3. TS2339: Property 'defaultProps' does not exist on type '(props: LayoutProps) => StatelessComponent<{}>'


interface ItemInterface {
  name: string,
  href: string,
  i18n?: string[]
}

interface LayoutHeaderItemProps extends ItemInterface{
  lang: string,
  activeHref: string,
}
function LayoutHeaderItem (props: LayoutHeaderItemProps): React.SFC{
  const {name, href, lang, activeHref, i18n} = props
  const hrefLang = /\//.test(href) ? `/${lang}` : ''
  if (!i18n.includes(lang)) return null
  return (
    <a
      className={`item${href === activeHref ? ' active' : ''}`}
      key={href}
      href={hrefLang + href}
    ><span>{name}</span></a>
  )
}

LayoutHeaderItem.propTypes = {
  lang: string,
  activeHref: string,
  name: string,
  href: string,
  i18n: array
}
LayoutHeaderItem.defaultProps = {i18n: ['cn', 'en']}
Run Code Online (Sandbox Code Playgroud)

Ale*_* L. 7

返回类型不是组件,函数本身是组件:

const LayoutHeaderItem: React.SFC<LayoutHeaderItemProps> =
    (props: LayoutHeaderItemProps) => { 
        // ... 
    }
Run Code Online (Sandbox Code Playgroud)

这个问题有点老了,SFC不建议FunctionComponent使用FC别名

  • 为了使用`React.StatelessComponent`,必须使用ES6箭头功能语法吗?我也希望使用`function(){}`函数声明语法。 (2认同)