在反应中使用打字稿,无状态组件不可分配到类型“React.SFC" [英] Using typescript in react,stateless component not assignable to type 'React.SFC'

查看:21
本文介绍了在反应中使用打字稿,无状态组件不可分配到类型“React.SFC"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

TypeScript: 2.8.3
@types/react: 16.3.14

函数组件中返回的类型是JSX.Element,当我将组件声明为React.SFC(React.StatelessComponent>).

The type of return in function component is JSX.Element, when I declare the component to React.SFC(alias of React.StatelessComponent).

出现三个错误:

  1. TS2322:类型 'Element' 不可分配给类型 'StatelessComponent<{}>',类型 'Element' 不匹配签名 '(props: { children?: ReactNode; }, context?: any): ReactElement'

TS2339:属性 'propTypes' 不存在于类型 '(props: LayoutProps) =>StatelessComponent<{}>'

TS2339:属性 'defaultProps' 不存在于类型 '(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']}

推荐答案

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

The return type is not a component, the function itself is a component:

const LayoutHeaderItem: React.SFC<LayoutHeaderItemProps> =
    (props: LayoutHeaderItemProps) => { 
        // ... 
    }

这个问题有点老了,SFC 已弃用,取而代之的是带有 FC 别名的 FunctionComponent

This question is a bit old, SFC deprecated in favor of FunctionComponent with a FC alias

const LayoutHeaderItem: React.FC<LayoutHeaderItemProps> =
    (props: LayoutHeaderItemProps) => { 
        // ... 
    }

这篇关于在反应中使用打字稿,无状态组件不可分配到类型“React.SFC"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆