Der @types/react
中,全局 JSX
-Namespace ist veraltet:
declare global { /** * @deprecated Use `React.JSX` instead of the global `JSX` namespace. */ namespace JSX { ... } }
Seit ich ESLints deprecation/deprecation
規(guī)則(來自插件 eslint-plugin-deprecation
aktiviert habe, erhalte ich jetzt eine Fehlermeldung für den Rückgabetyp der Funktionskomponente wie folgt:
export default function TestComponent(): JSX.Element { // This JSX is marked as deprecated return ( <span>Test</span> ); }
Seit global JSX
命名空間已被棄用,那么在這種情況下 JSX.Element
was ist der richtige Rückgabetyp-Ersatz?
Ist es React.JSX.Element
wie in der Einstellungsmeldung angegeben:
export default function TestComponent(): React.JSX.Element { ... }
oder ReactElement
so:
import { ReactElement } from "react"; export default function TestComponent(): ReactElement { ... }
Oder noch besser: Deklarieren Sie die Funktionskomponente mit React.FC
und lassen Sie TypeScript den Rückgabetyp ableiten, etwa so:
export const TestComponent: React.FC = () => { ... };
直接使用React.ReactElement
(或者更準確地說,React.ReactElement | null
):
import { ReactElement } from "react"; export function TestComponent(): ReactElement | null { return ( Math.random() < 0.5 ? null : <> A single Element (could be a Fragment like here) </> ); }
這正是(不再推薦)React.FC
強制執(zhí)行:
interface FunctionComponent<P = {}> { (props: P, context?: any): ReactElement<any, any> | null; // ... }
type JSXElementConstructor<P> = | ((props: P) => ReactElement<any, any> | null) // Case of a Function Component | (new (props: P) => Component<any, any>); // Case of a Class-based Component
話雖這么說,除非您有一些規(guī)則強制您輸入函數(shù)組件返回類型,否則您可以為了簡單起見而忽略它:
export function TestComponent() { // ... }
顯然,該功能現(xiàn)在可以返回任何內容,Typescript不會抱怨...除非您嘗試將其用作JSX模板中的功能組件,否則在fb/cra#8177:
const Example = () => <Component />; // Error here, due to Component returning the wrong thing