React中使用TypeScript:无状态组件无法赋值给React.SFC类型问题
Hey there! Let's break down what's going wrong here and fix those TypeScript errors one by one.
Root Cause
The main issue is that you've incorrectly annotated the return type of your LayoutHeaderItem function as React.SFC (an alias for React.StatelessComponent).
React.SFC is the type for the component function itself, not what the component returns. Your component returns a JSX element (or null), so that's the type you should use for the return value. This mismatch is causing all three errors you're seeing.
Fixes Step by Step
Let's address each error and apply the correct fixes:
1. Fix TS2322: Type Mismatch
Change the return type annotation from React.SFC to JSX.Element | null (since your component might return null when i18n doesn't include the current lang).
2. Fix TS2339: Missing propTypes/defaultProps Properties
To add these properties correctly, you can either let TypeScript infer the component type (simplest) or explicitly type the component as React.FC<LayoutHeaderItemProps> (the modern alias for React.SFC).
Also, note that propTypes need to use the PropTypes library's type definitions (not raw TypeScript types like string or array).
Corrected Code
First, ensure you have prop-types installed (npm install prop-types @types/prop-types if you haven't already), then here's the fixed version:
import PropTypes from 'prop-types'; // Don't forget to import PropTypes interface ItemInterface { name: string, href: string, i18n?: string[] } interface LayoutHeaderItemProps extends ItemInterface{ lang: string, activeHref: string, } // Explicitly type the component as React.FC (works with React.SFC too for your TS version) const LayoutHeaderItem: React.FC<LayoutHeaderItemProps> = (props) => { const {name, href, lang, activeHref, i18n} = props; const hrefLang = /\//.test(href) ? `/${lang}` : ''; if (!i18n?.includes(lang)) return null; // Added optional chaining for safety return ( <a className={`item${href === activeHref ? ' active' : ''}`} href={`${hrefLang}${href}`} > <span>{name}</span> </a> ); }; // Use PropTypes library types instead of raw TypeScript types LayoutHeaderItem.propTypes = { lang: PropTypes.string.isRequired, activeHref: PropTypes.string.isRequired, name: PropTypes.string.isRequired, href: PropTypes.string.isRequired, i18n: PropTypes.arrayOf(PropTypes.string) }; LayoutHeaderItem.defaultProps = { i18n: ['cn', 'en'] };
Additional Notes
React.SFCis deprecated in newer React/TypeScript versions, soReact.FCis the preferred alias (though both work in your TS 2.8.3 setup).- The optional chaining (
i18n?.includes) adds safety against null/undefined errors ifi18nisn't provided (even withdefaultProps, it's a good practice). - The
keyprop on the<a>tag isn't necessary here unless this component is rendered inside a list (like amaploop) — keys are meant for list items, not individual components.
内容的提问来源于stack exchange,提问作者ChuanfengLai

