首頁  >  問答  >  主體

棄用全域 JSX 命名空間後,JSX.Element 的正確回傳類型替換是什麼?

@types/react 中,全域 JSX 命名空間已被棄用:

declare global {
    /**
     * @deprecated Use `React.JSX` instead of the global `JSX` namespace.
     */
    namespace JSX {
    ...
    }
}

由於我啟用了 ESLint 的 deprecation/deprecation 規則(來自外掛程式 eslint-plugin-deprecation),我現在收到如下函數元件傳回類型的錯誤:

export default function TestComponent(): JSX.Element { // This JSX is marked as deprecated
    return (
        <span>Test</span>
    );
}

既然全域 JSX 命名空間已被棄用,那麼在這種情況下 JSX.Element 的正確回傳類型替換是什麼?

它是 React.JSX.Element 嗎,如棄用訊息中所述:

export default function TestComponent(): React.JSX.Element { ... }

或是 ReactElement 像這樣:

import { ReactElement } from "react";
export default function TestComponent(): ReactElement { ... }

或最好使用 React.FC 宣告函數元件並讓 TypeScript 推斷回傳類型,如下所示:

export const TestComponent: React.FC = () => { ... };


#
P粉404539732P粉404539732328 天前629

全部回覆(2)我來回復

  • P粉465287592

    P粉4652875922023-10-27 11:55:24

    使用React.JSX


    或從 "react" 匯入 JSX

    import {JSX} from 'react'
    

    回覆
    0
  • P粉521748211

    P粉5217482112023-10-27 00:02:44

    直接使用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 強制執行:

    interface FunctionComponent<P = {}> {
      (props: P, context?: any): ReactElement<any, any> | null;
      // ...
    }

    它也是 JSXElementConstructor

    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

    話雖這麼說,除非您有一些規則強制您輸入函數元件返回類型,否則您可以為了簡單起見而忽略它:

    export function TestComponent() {
      // ...
    }

    顯然,該功能現在可以返回任何內容,Typescript不會抱怨...除非您嘗試將其用作JSX模板中的功能組件,否則在fb/cra#8177

    const Example = () => <Component />; // Error here, due to Component returning the wrong thing

    回覆
    0
  • 取消回覆