在 @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 = () => { ... };
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
使用
React.JSX。或者从
"react"导入JSX:import {JSX} from 'react'直接使用
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:话虽这么说,除非您有一些规则强制您输入函数组件返回类型,否则您可以为了简单起见而忽略它:
export function TestComponent() { // ... }显然,该功能现在可以返回任何内容,Typescript不会抱怨...除非您尝试将其用作JSX模板中的功能组件,否则在fb/cra#8177: