在react中使用typescript,无状态组件不可分配到类型“React.SFC”

IT技术 reactjs typescript
2021-04-12 04:53:10

typescript:2.8.3
@types/react:16.3.14


JSX.Element当我将组件声明为React.SFC(的别名 React.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']}
1个回答

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

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

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

const LayoutHeaderItem: React.FC<LayoutHeaderItemProps> =
    (props: LayoutHeaderItemProps) => { 
        // ... 
    }
为了使用React.StatelessComponent必须使用ES6 箭头函数语法吗?我也希望使用function() {}函数声明语法。
2021-05-25 04:53:10
@MichaelR 你不能按原样使用它。相关建议在这里如果你真的有使用功能,您将需要分别输入参数和返回值类型(Parameters并且ReturnType可以使用佣工)
2021-05-27 04:53:10