typescript 在反应中使用打字稿,无状态组件不可分配到类型“React.SFC”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50440951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:25:16  来源:igfitidea点击:

Using typescript in react,stateless component not assignable to type 'React.SFC'

reactjstypescript

提问by codelegant

TypeScript: 2.8.3
@types/react: 16.3.14

打字稿:2.8.3
@types/反应:16.3.14



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

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

There are three errors occured:

出现了三个错误:

  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<{}>'

  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']}

回答by Aleksey L.

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

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

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

This question is a bit old, SFCdeprecated in favor of FunctionComponentwith a FCalias

这个问题是有点老了,SFC赞成不赞成使用的FunctionComponent一个FC别名