Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
991 views
in Technique[技术] by (71.8m points)

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

TypeScript: 2.8.3
@types/react: 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).

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


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']}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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, SFC deprecated in favor of FunctionComponent with a FC alias

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...